문제

<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