1

我在 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 无法绑定事件。可能是什么问题?

4

1 回答 1

3

您的代码中有几个问题。

首先:

var buttons = $("a#button");

这将选择一个带有 id 的锚元素button。由于 id 应该是唯一的,因此它应该只返回一个元素。但是,您正在尝试遍历返回的值。那不应该像您尝试那样工作。

第二:

如果您有一组您选择的 jQuery 对象,您通常会使用它.each()来迭代它们。然而,如果您尝试将事件处理程序绑定到一组对象,您甚至不必在循环中执行此操作,因为 jQuery 能够将事件绑定到选择。

第三:

.bind()-ing 的工作方式不同,您将.bind()- 语法与addEventListener语法混合在一起。

因此,要将您工作的非 jQuery 示例(不使用 jQuery 顺便说一句也不错)翻译成 jQuery,如下所示:

$('#button1').bind('touchstart', select);
$('#button1').bind('touchend', unselect);

function select(){
alert('test');
}

function unselect(){
alert('unselect');
}
于 2012-04-03T07:25:48.540 回答