我在 Backbone 中有以下模板,所有模板都完美呈现。
<a href="#list" data-role="button" id="button" class="all-unselected"></a>
<a href="#" data-role="button" id="button" class="suggested-unselected"></a>
<a href="#" data-role="button" id="button" class="friends-unselected"></a>
<a href="#" data-role="button" id="button" class="private-unselected"></a>
<a href="#" data-role="button" id="button" class="buzz-unselected"></a>
<script type="text/javascript">
var buttons = $("a#button");
for(var i=0; i<buttons.length; i++){
$(buttons[i]).bind('touchstart', select, false);
$(buttons[i]).bind('touchend', unselect, false);
}
function select(){
alert('test');
}
function unselect(){
alert('unselect');
}
</script>
但是,如果我编写以下内容,则不会触发 touchstart:
<a href="#" data-role="button" id="button1" class="suggested-unselected"></a>
<script type="text/javascript">
document.getElementById('button1').addEventListener('touchstart', select, false);
function select(){
alert('test');
}
function unselect(){
alert('unselect');
}
</script>
它有效。好像 jQuery 无法绑定(bind)事件。可能是什么问题?
最佳答案
您的代码中存在一些问题。
首先:
var buttons = $("a#button");
这将选择一个带有 id button
的 anchor 元素。由于 id 应该是唯一的,因此这应该只返回一个元素。然而,您正试图遍历返回值。那不应该像您尝试的那样工作。
第二个:
如果你有一组你选择的 jQuery 对象,你通常使用 .each()
来迭代它们。然而,如果您尝试将事件处理程序绑定(bind)到一组对象,您甚至不必在循环中执行此操作,因为 jQuery 能够将事件绑定(bind)到选择。
第三:
.bind()
-ing 的工作方式不同,您正在混合使用 .bind()
- 语法和 addEventListener
语法。
因此,要将您的工作非 jQuery 示例(顺便说一句,不使用 jQuery 也不错)转换为 jQuery,这看起来像:
$('#button1').bind('touchstart', select);
$('#button1').bind('touchend', unselect);
function select(){
alert('test');
}
function unselect(){
alert('unselect');
}
关于jquery - 在 jQuery 中绑定(bind) 'touchstart' 事件不适用于 android phonegap 和 backbone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9988611/