简体   繁体   中英

Jquery: get text from dynamically generated button in new div

Here is some dynamically generated content with jquery.

<div id="response">
    <button id="high" class="btn-key-main">high</button>
    <button id="last" class="btn-key-main">last</button>
</div>

How do I get the content of the button that is clicked (high or last) in a div with id="solution"? Here's what I tried:

$("#response").on("click", 'button.btn-key-main', function() {
    $("#solution").html($(this).val());
});

Solved by @slicedtoad and @smerny

.val() should've been .html() or .text()

$("#solution").html($(this).html());

http://jsfiddle.net/o4fyqvk7/

$("#response").on("click", 'button.btn-key-main', function() {
    $("#solution").html($(this).text());
});

$('.selector').val is documented here: http://api.jquery.com/val/

If you want the text of a button use $('.selector').text() http://api.jquery.com/text/

Often it's a good idea to add a values to your buttons. Just use the HTML value='' attribute.

Then you can do things like change the visible language on the button without breaking JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM