Jquery assign onclick to li from link
I have a list of items
<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>
I want to be able to assign onclick links to onclick of li, and
My attempt is still with one click (since I assign the script to onclick and not to execute the script)
$('.list li').click(function() {
var launch = $('a.launch', this);
if (launch.size() > 0) { this.onclick = launch.attr('onclick'); }
});
Thanks in advance Tim
+5
5 answers
building the @Thomas Stock answer , the following code prevents double execution when clicking on the link instead of li, (got it from the jQuery website here )
$(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());
}
});
});
+7
Do you do this so that the entire li block is a click link instead of a simple element? If so, you can easily do this with CSS.
HTML:
<html>
<head>
<title>Testing Block Elements</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<ul id="menu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
<li><a href="#">Link 5</a></li>
</ul>
</body>
</html>
CSS
#menu {
list-style: none;
padding: 0;
margin: 0;
}
#menu li {
/* Added to show the whole li element will be a clickable link. */
width: 250px;
border: 1px solid #000000;
}
#menu li a {
display: block;
}
EDIT:
click , javascript, .
+6