问题
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