2014-07-26 90 views
2

我想使用jquery选择列表锚链接。虽然在控制台输出中显示的页面中不存在'list'链接,但似乎'click'仍然被触发。什么可能导致“列表”和“添加”触发? 我使用jQuery 1.10.2这个简单的代码:JQuery锚链接选择器问题

<!-- <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/

回答

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/

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'); 
    }); 
}); 

否则它会被称为当事件监听器被设置时,而不是实际的事件。

2

你需要的是,当这个事件发生时调用这个函数,目前内部事件的方法被调用在页面加载事件声明函数作为自己的人生使命的方式是不正确的:

这样做:

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

UPDATED FIDDLE