Select a Tag with a Selector from a Text Variable using jQuery
I have a string which contains text and some <a>
tags in it; I want to know how 开发者_如何学GoI 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 : ''));
});
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);
Replace
$('a', text).each(function() {
with
$(text, 'a').each(function() {
and see if it works.
精彩评论