JQuery锚链接选择器问题

时间:2014-07-26 15:28:55

标签: javascript jquery html

我尝试使用jquery选择列表锚链接。虽然'列出'链接不存在于控制台输出中显示的页面中,它似乎点击了'仍然被触发。什么可能导致'列出'并且'添加'引起? 我使用jquery 1.10.2这个简单的代码:

<!-- <a href="#list">List</a> -->
<a href="#delete">Delete</a>
<a href="#add">Add</a>

<script>
    jQuery(document).ready(function($) {
        if ($('a[href$="#list"]').length>0){
            console.log('list found');
        }else{
            console.log('list not found');
        }

        function opentab(value){
            console.log('opentab: ' + value );
            //perform task here            
        }

        $(document).on('click', 'a[href="#list"]', opentab('list'));
        $(document).on('click', 'a[href="#add"]', opentab('add'));
    });
</script>

控制台输出:

list not found
opentab: list
opentab: add

这里有jsfiddle链接:http://jsfiddle.net/2FHf6/

3 个答案:

答案 0 :(得分:2)

你需要声明一个函数,当这个事件发生时调用这个函数,当前在页面加载时调用事件内部的方法,因为你的调用方式不正确:

这样做:

$(document).on('click', 'a[href="#list"]', function(){
            opentab('list')
        });
        $(document).on('click', 'a[href="#add"]', function(){
            opentab('add')
        });

UPDATED FIDDLE

答案 1 :(得分:1)

 $(document).on('click', 'a[href="#list"]', function(e){ 
         opentab('list');
 });
 $(document).on('click', 'a[href="#add"]', function(e){
        opentab('add');
 });

演示:

http://jsfiddle.net/XJhN6/

答案 2 :(得分:1)

请参阅此更新fiddle

如果要在触发的事件上调用函数并且函数需要传递值,则必须在“包装器”函数中执行此操作,如下所示:

jQuery(document).ready(function($) {
    if ($('a[href$="#list"]').length>0){
        console.log('list found');
    }else{
        console.log('list not found');
    }

    function opentab(value){
        console.log('opentab: ' + value );
        //perform task here            
    }

    $(document).on('click', 'a[href="#list"]', function() {
        opentab('list');
    });
    $(document).on('click', 'a[href="#add"]', function() {
        opentab('add');
    });
});

否则,将在设置事件侦听器时调用它,而不是在实际事件上调用。