How can I replace html text dynamically?

喜欢而已 提交于 2019-12-11 06:48:53

问题


I'm adding the text "I Tot I Taw a Puddy Tat!" to the top of a page with jQuery this way in the ready function:

$("#Twitterati").html("<h3>I Tot I Taw a Puddy Tat!</h3>").append(tweetiePie);

...but I want to dynamically replace that placeholder text ("I Tot I Taw a Puddy Tat!") with the contents of this text input control:

<input type="text" name="inputQuery" id="inputQuery" placeholder="Enter something" style="display: inline-block;" />

...when the Enter key is mashed. How can I do that?

I tried this:

$("#inputQuery").keyup(function(e) {
    if(e.keyCode == 13) {
        $("#Twitterati h3").val($("#inputQuery".val()));
    }
});

...and this:

$("#inputQuery").keyup(function(e) {
    if(e.keyCode == 13) {
        $("#Twitterati h3").replaceWith($("#inputQuery".val()));
    }
});

...but neither one did anything, that I could see...

UPDATE

This is working pretty well, now; but I want the tweets to refresh when the inputQuery val replaces the text/caption/heading, too. IOW, I can change the text from, say, "jquery" to "html5" but the tweets I've got displaying remain the jquery tweets. How can I get that div to refresh?


回答1:


Try this:

$("#inputQuery").keyup(function(e) {
    if(e.keyCode == 13) {
        $("#Twitterati h3").html($(this).val());
    }
});

Missing a closing bracket here $("#inputQuery" <----
and a extra bracket at last .val())); <----




回答2:


Fix this line

                                        v
$("#Twitterati h3").html($("#inputQuery").val());

Use .html() instead of .val() for the h3




回答3:


You want to set the HTML of the target element. Also, you can use "this" instead of targeting the element by ID again

$("#inputQuery").keyup(function(e) {
    if(e.keyCode == 13)
        $("#Twitterati h3").html($(this).val());
});



回答4:


Bit Safer

$("#inputQuery").keyup(function(e) {
    if(e.keyCode == 13) {
        $("#Twitterati h3").text(this.value);
    }
});



回答5:


You are missing closing braket that leads error and replace .val() with .html because you are replacing text not value

$("#Twitterati h3").html($("#inputQuery").val());

but your original was

$("#inputQuery".val())    //MIssing HERE

You can use this also like

$("#Twitterati h3").html($(this).val());

'this' will automatically indicates the inputQuery




回答6:


replace "#inputQuery".val()

with

$("#inputQuery").val()

CODE IS:

$("#inputQuery").keyup(function(e) {
    if(e.keyCode == 13) {
        $("#Twitterati h3").html($("#inputQuery").val());
    }
});


来源:https://stackoverflow.com/questions/16557053/how-can-i-replace-html-text-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!