为什么单击按钮之前运行的jQuery("click","button",...)?

aba*_*ter 0 javascript jquery onclick

我只是学习jquery,而且我遇到了我不理解的行为.我有:

HTML:

<div id="tour" data-location="london">
    <button>Get Photos</button>
    <ul class="photos"></ul>
</div>
Run Code Online (Sandbox Code Playgroud)

和jquery:

var tour = {
    init: function () {
        $("#tour").on("click", "button", alert("clicked"));
    }
};
$(document).ready(function () {
    alert("hello");
    tour.init();
});
Run Code Online (Sandbox Code Playgroud)

正如我所料,在加载dom之后出现"hello"警报.然而,"点击"警报也会被触发,并且在按下按钮时不会随后触发.

http://jsfiddle.net/abalter/295sgf5c/2/

Jos*_*ier 7

如果您希望在单击按钮时执行它,则需要将其包装在函数中:

更新的示例

var tour = {
    init: function () {
        $("#tour").on("click", "button", function () {
            alert("clicked")
        });
    }
};
Run Code Online (Sandbox Code Playgroud)


Ted*_*Ted 5

看到这个小提琴.

你的回调需要是一个函数,如下所示:

var tour = {
    init: function () {
        $("#tour").on("click", "button", function(e){alert("clicked")});
    }
};
Run Code Online (Sandbox Code Playgroud)