HTML
<button id="add_div"> show more </button>
JQUERY
每当我单击显示值时,我添加的类“ show_div_value”越多,警报显示的越多
var inc_numbers;
$("#add_div").click(function() {
inc_numbers += 1;
$('parent_div').append('<button id="'+ inc_numbers +'" class="
show_div_value" value="inc_numbers"></button><button class="
show_button" id="'+ inc_numbers +'"> show value </button>');
//DISPLAYS 2 buttons with the same ID
});
$(".show_button").click(function() {
var get_btn_id = $(this).attr('id');
$(".show_div_value").each(function() {
var get_div_id = $(this).attr('id');
if(get_btn_id == get_div_id) {
alert($(this).val());
return false; //I put this here but it doesn't seem to work out
}
});
});
答案 0 :(得分:1)
您应按以下方式更新代码:
var inc_numbers = 0;
$('#add_div').click(function() {
inc_numbers += 1;
$('#parent_div').append( // Not $('parent_id').append()!
'<button data-id="' + inc_numbers + '" class="show_div_value" value="' + inc_numbers + '" style="display: none;"></button>' +
'<button class="show_button" id="' + inc_numbers + '"> show value </button>'
);
// Same id to two elements is invalid in HTML, so I use data- attributes.
// This will do the jQuery code very simple,
// beacuse I just need to select the .show_div_value with data-id equals to the id of the clicked button
});
$('#parent_div').on('click', '.show_button', function() {
// Don't attach the listener directly to the button, because the button doesn't exist when you atatch the listener.
// Because of this, you should use delegated event. See https://learn.jquery.com/events/event-delegation/.
var div = $('.show_div_value[data-id=' + $(this).attr('id') + ']');
console.log(div.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add_div"> show more </button>
<div id="parent_div"></div>