jQuery通过链接为li分配onclick [英] jquery assign onclick for li from a link
本文介绍了jQuery通过链接为li分配onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个物品清单
<ul class="list">
<li>
<a href="#Course1" class="launch" onclick="alert('event 1')">event 1</a>
</li>
<li class="alt">
<a href="#Course2" class="launch" onclick="alert('event 2')">event 2</a>
</li>
<li>
<a href="#Course3" class="launch" onclick="alert('event 3')">event 3</a>
</li>
<li class="alt">
<a href="#Course4" class="launch" onclick="alert('event 4')">event 4</a>
</li>
</ul>
我希望也可以将链接的onclick分配给li的onclick
I want to be able to assign the onclick of the link to the onclick of the li aswell
到目前为止,我的尝试是落后一击(因为我是将脚本分配给onclick而不是执行脚本)
My attempt so far is one click behind (as I am assigning the script to the onclick rather than executing the script)
$('.list li').click(function() {
var launch = $('a.launch', this);
if (launch.size() > 0) { this.onclick = launch.attr('onclick'); }
});
先谢谢了 蒂姆
推荐答案
基于 @Thomas Stock's answer 以下代码可防止在单击时重复执行链接代替李. (从此处 jQuery网站获取它)
building on @Thomas Stock's answer the following code prevents double execution on clicking on link instead of li. (got it from here jQuery site)
$(document).ready(function() {
$('ul.list li').click(function(e) {
var $target = $(e.target);
if(!$target.is("li")) //magic happens here!!
{
return;
}
var launch = $('a.launch', this);
if (launch.size() > 0)
{
eval(launch[0].onclick());
}
});
});
这篇关于jQuery通过链接为li分配onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文