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 wo开发者_如何学运维rking... 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?
You can bind all buttons with a click event like this, there is no need to loop through them
$(function(){
$("button").click(function() {
alert($(this).attr("value"));
});
});
But a more precise selector might be:
$(function(){
$("button[id^='button-'").click(function() {
alert($(this).attr("value"));
});
});
You're missing a );
, and make sure your code is in a document.ready
handler, like this:
$(function() {
$('button').each(function() {
$(this).click(function() {
alert($(this).val());
}); //missing ); here!
});
});
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:
$(function() {
$('button').click(function() {
alert($(this).val());
});
});
You are missing )
:
$('button').each(function(){
$(this).click(function(){
alert($(this).val());
});
});
Yup. Try this:
$('button').click(function() {
alert($(this).val());
});
You may also want a return false
or .preventDefault()
in there.
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
$("button").click(function(){
alert($(this).attr("value"));
});
精彩评论