将Click / vclick事件绑定到JQueryMobile中的按钮的正确方法是什么?
我已尝试使用$().bind("click", function(){});
和$().on("click", function(){});
,但我从来没有收到控制台的回复。
我的index.html中设置了这样的按钮:
修改
<div data-role="page" data-title="OneStop Mobile" class="ui-responsive-panel" id="homepage">
<div data-role="panel" data-dismissable="false" id="optionsPanel">
<div>
<ul data-role="listview">
<li> <a href="#" id="store">store</a> </li>
<li> <a href="#" id="download">Download</a> </li>
<li> <a href="#" id="check">Check</a> </li>
<li> <a href="#" id="clear">Clear</a> </li>
<ul>
</div>
</div>
</div>
我在index.js中绑定它:
$("#store").bind("click", function(event, ui) {
console.log("WORK DAMNIT!")
});
根据JQMobile api和演示页面,这应该可行,但我从未在设备或浏览器中看到任何事情。
答案 0 :(得分:0)
您的问题是,在绑定事件时,您绑定它的元素还不是DOM
的一部分。
您需要确保在绑定事件时,通过在DOM
事件或JQM的pageinit中调用您的函数,该元素已经成为ready
的一部分页面,或者您可以通过调用.on函数的重载版本来使用事件委派。
例如
pageinit
事件期间的绑定(这也确实使用事件委托绑定到pageinit
事件)。
//passing in the selector as the second parameter calls the overloaded version of .on
$(document).on('pageinit', '#myStorePage', function() {
$("#store").bind("click", function(event, ui) {
console.log("This should Work!")
});
});
将.on与事件委托一起使用
$(document).on('click', '#store', function() {
console.log('This should Work!');
});
请注意,事件委派的工作方式是将事件绑定到现有的更高级别元素,然后在事件冒泡时检查选择器。通常,您实际上希望将事件绑定到尽可能接近您检查的元素,但如果需要,您可以一直到文档。
作为使用第一种方法提到的Omar的旁注,我提供的.bind和.on一样有用。但是从jQuery 1.7开始,.bind只委托给.on,这是首选的(为了向后兼容而留下了.bind
)..
答案 1 :(得分:0)
$(document).on('click','#store', function(event) {
alert("WORK DAMNIT!")
});