使用jQuery从文本变量中选择带有选择器的标签 [英] Select a Tag with a Selector from a Text Variable using jQuery

查看:127
本文介绍了使用jQuery从文本变量中选择带有选择器的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其中包含文本和一些<a>标记;我想知道如何从变量中选择标签并对其进行循环.我尝试了以下操作,但没有成功:

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 : ''));

        });

推荐答案

您需要将文本包装在div(或其他元素)中,然后find()将其包装:

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);

这篇关于使用jQuery从文本变量中选择带有选择器的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆