有人告诉我,最好将事件绑定到元素上,而不是到处都是函数的onclick
。我同意这一点,因为它从HTML中下放了更多,这意味着更干净、更容易调试代码。
但是我在做这件事上遇到了麻烦!我使用PHP遍历一些数据(见下文),目前我使用onclick来调用函数。如何使用JQuery将此onclick事件绑定到多个元素。
<?php foreach($main_tags as $key=>$value){ ?>
<li>
<a id="<?php echo $key; ?>" href="#" onclick="tag_search('<?php echo $key; ?>'); return false;">
<?php echo $key; ?>
<span class="num-active">
<?php echo $value; ?>
</span>
</a>
</li>
<?php } ?>
感谢所有人的帮助
发布于 2010-06-14 04:19:24
<ul id="container">
<?php foreach($main_tags as $key=>$value){ ?>
<li>
<a href="#" key="<?php echo $key;?>">
<?php echo $key; ?>
<span class="num-active">
<?php echo $value; ?>
</span>
</a>
</li>
<?php } ?>
</div>
<script>
$(function() {
function tag_search(){};
$('#container a').click(function(e) {
e.preventDefault();
tag_search.call( this, $(this).attr('key') );
});
});
</script>
发布于 2010-06-14 04:29:14
你可以使用iterate over a group of divs or lis or whatever with JQuery。
下面的代码没有显示php,它使用警报来显示JQery发生了什么……我评论了实际的代码……希望能有所帮助。这样你就不必担心is了,因为条目的顺序才是最重要的。当然,您可以将ids留在其中。
编辑-添加了如何处理自定义密钥
案例1:数字键
<!DOCTYPE html>
<html lang="en">
<head>
<title>Binding events</title>
<script type="text/javascript" src="JQUERY-PATH/jquery-1.4.2.min.js"></script>
<meta charset="utf-8" />
<script type="text/javascript">
// When the page is ready ==================================================
$(document).ready(function()
{
$('li').each(function(index)
{
// The line below would read something like:
// $(this).click( function () {tag_search(index)});
$(this).click( function() { alert("This would trigger => tag_search(" + index + ")")});
});
});
</script>
</head>
<body>
The php goes into the unordered list:
<ul>
<li>zero</li>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
</ul>
</body>
</html>
案例2:您选择的自定义密钥
如果你有全是数字的键,你可能想在前面加上一个任意的字母,这样它就可以验证id或类名。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Binding events</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<meta charset="utf-8" />
<script type="text/javascript">
// When the page is ready ==================================================
$(document).ready(function()
{
$('li').each(function(index)
{
// The line below would read something like:
// $(this).click( function () {tag_search($(this).attr('id'))});
$(this).click( function() { alert("This would trigger => tag_search(" + $(this).attr('id') + ")")});
});
});
</script>
</head>
<body>
The php goes into the unordered list:
The custom keys are placed in ids or classes:
<ul>
<li id="Roger">zero</li>
<li id="Dodger">one</li>
<li id="23884">two</li>
<li id="Fubar">three</li>
<li id="Gungho">four</li>
<li id="Burlap">five</li>
</ul>
</body>
</html>
https://stackoverflow.com/questions/3033730
复制相似问题