Select a Tag with a Selector from a Text Variable using jQuery

好久不见. 提交于 2019-12-12 02:31:12

问题


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

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