Dynamically created button text

时间:2016-04-07 10:49:03

标签: javascript jquery

I'm creating 2 buttons dynamically.

How can I change button text? Below is what I tried but it doesn't work.

$(document).on('click', '.class', function(e){
    var thisbut = this.id;
    $.post('my.php',{ val: val1 }, function(done){
         document.getElementById(thisbut).innnerHTML = "Button Text New";
    });
});

2 个答案:

答案 0 :(得分:7)

innnerHTML should be innerHTML, and your code will only work if the buttons all have a unique ID.

Instead you can directly use the element - there is no need to reselect it by ID:

this.innerHTML = "Button Text New";

Or jQuery:

$(this).text("Button Text New");

After the edited question:

You can assign the button to a variable like below and then use it in the success handler. Simply using this in the success handler won't work because the this context has changed, so by storing the button in a variable you can keep it for further use:

$(document).on('click', '.class', function(e){
    var thisbut = this;
    $.post('my.php',{ val: val1 }, function(done){
         thisbut.innnerHTML = "Button Text New";
         // or jQuery:
         $(thisbut).text("Button Text New");
    });
});

答案 1 :(得分:1)

尝试使用$(this)来获取元素的id

$(document).on('click', '.class', function(e){
    var thisbut = $(this).attr("id");
    document.getElementById(thisbut).innerHTML = "Button Text New";
});