jQuery get text

馋奶兔 提交于 2019-12-23 05:14:23

问题


I have a function that returns some html like this:

return ("<span class='opt'>some text</span>");

I use it within the success callback function in $.ajax:

$.ajax({
    url: uri,
    cache: false,
    success: function(html){
       $(tag).append(format(html));
    }
});

html give the <span></span> element. I want to retrieve just the text without the tags. I tried it using format(html).text() but it does not work. Any ideas?


回答1:


If you want to do jQuery operations on a string of HTML, use jQuery to convert it first:

var newContent = $(format(html)); // use the results of `format(html)` to make a jQuery selection
$(tag).append(newContent.text()); // use the jQuery text method to get the text value of newContent

See the API for an explanation of how this works.




回答2:


$('<span class="opt">some text</span>').text() should do the job or in your case:

$(tag).append($(format(html)).text());



回答3:


$(tag).append($(format(html)).text());

That will take the text "<span>...</span>", convert it into a jQuery object, and extract the text, leaving behind the tags.



来源:https://stackoverflow.com/questions/4705474/jquery-get-text

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