I have checked some of the similar questions which were asked.
I want to add/delete buttons when users click the add/delete buttons dynamically. Therefore, each button has to have a unique id to identify themselves.
Here is p开发者_运维问答art of the html code:
<p id="q1">Question: 1<input type="text" class="ttt"/>
<button class="buttonPlus" type="button"></button>
<button class="buttonMinus" type="button" id="1"></button></p>
Here is part of the jQuery code:
var questionCount = 1;
$("#q1").append("<p id='p2'>Question: " + ++questionCount + "<input type='text'>\
<button type='button' class='buttonPlus'></button>\
<button type='button' class='buttonMinus' id=questionCount></button></p>");
//Re-binding
var newBtnPlus = $("#q1").find('.buttonPlus:last');
var newBtnMinus = $("#q1").find('.buttonMinus:last');
newBtnPlus.click(function(){
btnPlsClickEvent(newBtnPlus);
});
newBtnMinus.click(function () {
btnMnsClickEvent(newBtnMinus);
});
function btnMnsClickEvent(btn) {
var idNum = $(this).attr("id");
alert(idNum);}
Besides the method above, I have tried: alter(this.id); alter(btn.id); .etc.
I don't know why I can't get the id I have dynamically assigned to the minus buttons, nor can I get the statically assigned one which is done by the html.
I have been stuck by this question for hours. Could you help me?
Thanks, Ashley
Simply pass a reference to the button when you go to call the generic function:
newBtnMinus.click(function () {
btnMnsClickEvent(this); // use "this" instead of your selector object
});
function btnMnsClickEvent(btn) {
var idNum = btn.id; // now reference the button you pass
alert(idNum);
}
No need to use $(this).attr('id')
when you can simply use this.id
$('button').click(function(){
alert(this.id);
});
精彩评论