jquery - 每个/单击功能不起作用
编辑:这有效,但不确定为什么?
$('button').each(function() {
$(this).bind(
"click",
function() {
alert($(this).val());
});
});
我不确定为什么这不起作用...现在,我只是尝试输出带有按钮值的警报,但它是无法在我的页面上工作。我在 Firebug 中没有收到任何控制台错误,也看不到任何阻止其工作的内容。
我的 HTML 看起来像这样:
<table id="addressbooktable">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>7892870</td>
<td><button id="button-20" class="custom-action" value="XY89" name="info">Click</button></td>
</tr>
<tr>
<td>9382098</td>
<td><button id="button-21" class="custom-action" value="XY544" name="info">Click</button></td>
</tr>
<tr>
<td>3493900</td>
<td><button id="button-22" class="custom-action" value="XY231" name="info">Click</button></td>
</tr>
</tbody>
</table>
代码看起来像这样:
$('button').each(function() {
$(this).click(function() {
alert($(this).val());
}
});
但是,单击它根本没有任何作用?是我使用方式不对吗?
EDIT: this works, but not sure why?
$('button').each(function() {
$(this).bind(
"click",
function() {
alert($(this).val());
});
});
I'm not sure why this isn't working... Right now, I'm just trying to output an alert with the button value, but it's not working on my page. I don't get any console errors in Firebug and can't see anything that would prevent it from working.
My HTML looks like this:
<table id="addressbooktable">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>7892870</td>
<td><button id="button-20" class="custom-action" value="XY89" name="info">Click</button></td>
</tr>
<tr>
<td>9382098</td>
<td><button id="button-21" class="custom-action" value="XY544" name="info">Click</button></td>
</tr>
<tr>
<td>3493900</td>
<td><button id="button-22" class="custom-action" value="XY231" name="info">Click</button></td>
</tr>
</tbody>
</table>
And the code looks like this:
$('button').each(function() {
$(this).click(function() {
alert($(this).val());
}
});
But, clicking on it does nothing at all? Am I using it incorrectly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将所有按钮与这样的单击事件绑定,无需循环它们
但更精确的选择器可能是:
You can bind all buttons with a click event like this, there is no need to loop through them
But a more precise selector might be:
您缺少
);
,并确保您的代码位于document.ready
处理程序中,如下所示:这样它才会运行,直到这些
You're missing a
);
, and make sure your code is in adocument.ready
handler, like this:This way it won't run until those
<button>
elements are in the DOM for$('button')
to find them. Also, you can run.click()
on a set of elements, like this:您缺少
)
:You are missing
)
:是的。试试这个:
您可能还需要其中的
return false
或.preventDefault()
。Yup. Try this:
You may also want a
return false
or.preventDefault()
in there.您不能对按钮使用
.val()
方法。您可以使用.attr()
来获取值属性。如果您使用自定义属性,请使用 data-attribute。尝试
You cannot use
.val()
method for button. You can use.attr()
to get the value attribute. If you are using custom attributes then use data-attribute.Try