jQuery two part question - anchor to mimic tab and binding click event
Question
I'd like to have an anchor in the page that performs the same function as the tab.
I was only able to get it to work if I placed something like$('#tabs ul a:first').click()
in the onclick event of the particular anchor. Note: the href has no effect on the links external to the tab plugin; it is probably only used in the anchors in the tab when constructing their click event.I came across a jQuery binding problem.
Instead of performing a DOM lookup for each link, it'd be better to store that in a variable and add the click event to the external anchor's click event. However, when a selector returns multiple objects, the object in the array (it's most likely not an array that's returned, but an object) does not seem to have any functions.
JSFiddle Example
JS$(function() {
$( "#tabs" ).tabs();
var tabs = $('#tabs ul li a');
$( "#links2 a" ).each(function(index){
$(this).bind('click',function(){
(tabs[index]).click();
});
});
});
HTML/CSS (incomplete)
<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" ><开发者_C百科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>
Instead of
(tabs[index]).click();
it should be
tabs.eq(index).click();
The first form gets you the raw DOM element, while the second gets you a jQuery-wrapped DOM element. There's no "click" method on <a>
element nodes, at least no standard method. (Alternatively, $(tabs[index])
would work too.)
精彩评论