Javascript - 开('点击') - 错误 - 调用页面加载

时间:2013-07-20 00:01:59

标签: javascript jquery onclick jquery-on clicklistener

<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>

无论是否单击该对象,此位代码都会在页面加载时触发。为什么呢?

3 个答案:

答案 0 :(得分:3)

你想要的是:

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

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

$(document).ready(playHandlers);

您的代码编写方式,当您在playController调用中注册时,它正在调用.on

jsfiddle

答案 1 :(得分:3)

您正在调用该函数,因此传递playController的结果。你可以这样做。

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

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

答案 2 :(得分:1)

这将起作用:
(演示here

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

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

这将在加载页面时加载代码并调用函数playHandlers()。您是直接调用它,因为您忘记在on / click调用中添加function(){}