开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜