<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>

<script>
    function playController(dataObj){
        alert(dataObj);
    }

    function playHandlers(){
        var dataObj = "stef";
        $('.audiocontrol').on('click', playController(dataObj));
    }

    $(document).ready(playHandlers);
</script>

This bit of code is firing off on page load whether I click the object or not. Why?

有帮助吗?

解决方案

What you want is:

function playController(dataObj){
    alert(dataObj);
}

function playHandlers(){
    var dataObj = "stef";
    $('.audiocontrol').on('click', function() { playController(dataObj); } );
}

$(document).ready(playHandlers);

The way your code was written, it was calling playController when you were registering it in the .on call.

jsfiddle

其他提示

You're invoking the function therefore passing the result of playController. You can do something like this.

function playHandlers(){
    var dataObj = "stef";

    $('.audiocontrol').on('click', function() {
        playController(dataObj);
    });
}

This will work:
(demo here)

function playController(dataObj) {
    alert(dataObj);
}

function playHandlers() {
    var dataObj = "stef";
    $('.audiocontrol').on('click', function () {
    playController(dataObj)
   });
}
$(document).ready(playHandlers);

This will load your code when the page loaded and call the function playHandlers(). You were calling it directly because you forgot to add function(){} in the on/click call.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top