【问题标题】:Replacing text within html element string替换html元素字符串中的文本
【发布时间】:2012-05-29 16:01:36
【问题描述】:

我有一个 div .content,其中有一个 HTML 表格作为 JavaScript 字符串。在.content 元素中,有一个 td .quantity 我需要更新字符串。

我刚试过这个:

var content = $('.content').html();
content = $(content).parent().children('.quantity').text("6"); // []
content = $(content).parent().children('.quantity').text("6").html(); // null

我只想输出带有更新值的字符串,有点像基于 DOM 的搜索和替换,有什么想法吗?

【问题讨论】:

    标签: jquery html string dom object


    【解决方案1】:

    在 .content 元素中,有一个 td .quantity 我需要更新 字符串。

    试试find()方法:

    var content = $('.content').html();
    $(content).find('.quantity').text("6");
    

    你也可以直接访问:

    $('.content').find('.quantity').text("6");
    

    【讨论】:

    • 这种工作给了我<td class="quantity>6</td>,但我需要整个表格回到content变量中。
    • @ThomasReggi:然后伸出父表,但尝试以类似的方式使用find 方法。
    【解决方案2】:

    你可以试试

    var content = $('.content table');
    $('.quantity', content).text('6').end(); // will return `table`
    

    DEMO

    你可以试试这个来获取字符串

    $('.quantity', content).text('6').end().parent().html();
    

    DEMO

    【讨论】:

    • 我需要它作为字符串返回,我该怎么做 .html() 不起作用。
    • $('.quantity', content).text('6').end(); 是一个对象。我需要它是一个字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2018-02-05
    • 2011-10-29
    • 2011-10-11
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多