【问题标题】:Scanning text in between two HTML elements and wrapping them with .wrapAll() function扫描两个 HTML 元素之间的文本并使用 .wrapAll() 函数包装它们
【发布时间】:2017-10-01 08:56:29
【问题描述】:

我正在开发一个论坛网页,但不允许在网页中编辑 HTML。我想隐藏文本,直到悬停在上面。这是 HTML 代码的粗略示例:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>nextUntil demo</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<dl>
    <dd class="postprofile-info">
        <span>
            <span>
                <img src="image here">
            </span>
        </span>
        "This is the text I want to surround in a div"
        <br>
        <span class="label"></span>
        "Text from here on out can be ignored"
        <br>
    </dd>
<dl>
</body>
</html>

我知道有 .nextUntil() 和 .wrapAll() 函数,但我就是无法让它正常工作。我遇到的另一个问题是比较标签和
标签之间的信息,以确保我只将我想要的文本包装在一个 div 中。我的目标是将该文本包装在一个 div 中,以便我可以给它一个类并使用 css 对其进行操作。

编辑 1: 我没有提供任何 JS 的原因是因为我只测试了使用 .nextUntil() 和 .wrapAll() 的片段。这就是我所拥有的一切,而且是零零碎碎的:

(只是测试看看这是否可行:)

$( ".postprofile-info" ).nextUntil( "dt" ).css( "background-color", "red" );

(另一个测试)

$('form > span').each(function(){
    $(this).next('p').andSelf().wrapAll('<div class="test"/>');
});

(另一个测试)

var nodelist = document.getElementsByTagName("dd").length;
for (i = 0; i < nodelist-1; i++) {
    var TextDd = document.getElementsByTagName("dd")[i].innerHTML;
    if (TextDd === "For helping in the construction of the CGDT Forum"){
        $('form > span').each(function(){
            $(this).next('p').andSelf().wrapAll('<div class="test"/>');
        });
    }
}

【问题讨论】:

  • “我只是无法让它正常工作”:您需要将您尝试过的 JS 添加到问题中,这样我们才能看到出了什么问题。还有,没有&lt;/dd&gt;标签吗?

标签: javascript jquery html wrapall nextuntil


【解决方案1】:

让事情变得不那么容易的是你试图包装一个文本节点。这不是那么容易找到的。但是这样的事情可以解决问题:

$('dl > dd').each(function(index){
    var textNode = $(this).contents().get(2).nodeValue;
    console.log(textNode);
    var newHtml = $(this).html().replace(textNode,'<div class="new">'+textNode+'</div>');
    $(this).html(newHtml);
});
.new {
    border: solid 3px green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
  <dd class="postprofile-info">
    <span>
        <span>
            <img src="image here">
        </span>
    </span>
    "This is the text I want to surround in a div"
    <br>
    <span class="label"></span>
    "Text from here on out can be ignored"
    <br>
  </dd>
</dl>

注意:如果您更改标记,这将不起作用,尤其是 .get(2) 的原因,因此文本节点必须恰好位于该位置。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2015-07-14
  • 2018-06-12
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
相关资源
最近更新 更多