问题
I have a string which contains text and some <a> tags in it; I want to know how I can select a tag from the variable and loop it. I tried the following but it didn't work:
var text = `some string here with <a href="#link">http:something.com</a> more string and more links also`;
$('a', text).each(function() {
var string = $(this).html();
$(this).html(string.substring(0, length-1)+(string.length > length ? end : ''));
});
回答1:
You need to wrap the text in a div (or other element) then find() it:
var text = 'some string here with <a href="#link">http:something.com</a> more string and more links also';
text = $('<div>' + text + '</div>');
text.find('a').each(function() {
var length = 10;
var end = '...';
var string = $(this).html();
$(this).html(string.substring(0, length) + (string.length > length ? end : ''));
});
var text = text.html();
// Put it into a textarea
$('#myTextarea').val(text);
回答2:
Replace
$('a', text).each(function() {
with
$(text, 'a').each(function() {
and see if it works.
来源:https://stackoverflow.com/questions/1553601/select-a-tag-with-a-selector-from-a-text-variable-using-jquery