我希望在页面中有一个与标签执行相同功能的锚点。
如果我在特定锚点的onclick事件中放置$('#tabs ul a:first').click()
之类的东西,我只能使它工作。注意:href对tab插件外部的链接没有影响;它可能仅在构造click事件时在选项卡中的锚点中使用。
我遇到了一个jQuery绑定问题。
不是为每个链接执行DOM查找,最好将其存储在变量中,并将click事件添加到外部锚点击事件中。但是,当一个选择器返回多个对象时,数组中的对象(它很可能不是返回的数组,而是一个对象)似乎没有任何函数。
$(function() {
$( "#tabs" ).tabs();
var tabs = $('#tabs ul li a');
$( "#links2 a" ).each(function(index){
$(this).bind('click',function(){
(tabs[index]).click();
});
});
});
<link rel="stylesheet" href="http://jqueryui.com/themes/base/jquery.ui.all.css" />
<link rel="stylesheet" href="http://jqueryui.com/demos/demos.css" />
<style type="text/css">
#links1 , #links2, #links3 { margin-top:1em; font-size:1.5em;}
#links1 a, #links2 a, #links3 a { text-decoration:none; color:#0cf}
</style>
<div id="tabs">
<ul>
<li><a href="#tabs-1">Foo</a></li>
<li><a href="#tabs-2">Bar</a></li>
<li><a href="#tabs-3">Baz</a></li>
</ul>
<div id="tabs-1" ><p>Foo foo foo foo foo foo foo foo. foo-foo!</p></div>
<div id="tabs-2" ><p>Bar bar bar bar bar bar bar bar. bar-bar!</p></div>
<div id="tabs-3" ><p>Baz baz baz baz baz baz baz baz. baz-baz!</p></div>
</div>
<div id="links1">
<div>HREF doesn't matter:</div>
<a href="#tabs-1">foo</a>
<a href="#tabs-2">bar</a>
<a href="#tabs-3">baz</a>
</div>
<div id="links2">
<div>Trying to dynamically bind onclick</div>
<a href="#">foo</a>
<a href="#">bar</a>
<a href="#">baz</a>
</div>
<div id="links3">
<div>What should happen, but not the right method:</div>
<a href="#" onclick="$('#tabs li:first a').click()">foo</a>
<a href="#" onclick="$('#tabs li a:eq(1)').click()//not sure if this is the best way to reference">bar</a>
<a href="#" onclick="$('#tabs li:last a').click()">baz</a>
</div>
答案 0 :(得分:2)
而不是
(tabs[index]).click();
应该是
tabs.eq(index).click();
第一个表单获取原始DOM元素,而第二个表单获取jQuery包装的DOM元素。 <a>
个元素节点上没有“click”方法,至少没有标准方法。 (或者,$(tabs[index])
也可以。)