gpt4 book ai didi

javascript - 为什么 ("click"、 "button"、...) 上的 jQuery 在单击按钮之前运行?

转载 作者:行者123 更新时间:2023-11-28 11:09:30 25 4
gpt4 key购买 nike

我刚刚学习 jquery,我遇到了我不理解的行为。我有:

html:

<div id="tour" data-location="london">
<button>Get Photos</button>
<ul class="photos"></ul>
</div>

和jQuery:

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

正如我所料,加载 dom 后会出现“hello”警报。但是,“单击”警报也会触发,并且在按下按钮时不会随后触发。

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

最佳答案

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

Updated Example

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

关于javascript - 为什么 ("click"、 "button"、...) 上的 jQuery 在单击按钮之前运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29609979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com