關閉並重新打開特定單詞周圍的標簽 - Close and reopen tag around specific word -开发者知识库

關閉並重新打開特定單詞周圍的標簽 - Close and reopen tag around specific word -开发者知识库,第1张

I need to close a <span> tag before the word "hello" and reopen it just after when a button is clicked.

我需要在單詞“hello”之前關閉標記,並在單擊按鈕后重新打開它。

Here is a Fiddle

這是一個小提琴

This is my code :

這是我的代碼:

<span class="border"> 
    border Hello border border
</span>
<div> 
    <span class="button">Style me !</span>
</div>

jQuery :

$('.button').click(function () {
    $('.border').each(function () {
        var t = $(this).text();
        var s = t.split('Hello').join('</span>Hello<span class="border">');
        $(this).html(s)
    });
});

The HTML output I have after clicking .button is :

點擊.button后我輸出的HTML輸出是:

<span class="border"> 
    border Hello<span class="border"> border border
</span>

And the output I want is :

我想要的輸出是:

<span class="border"> 
    border </span>Hello<span class="border"> border border
</span>

Why isn't the .join function inserting the </span> closing tag?

為什么.join函數不插入 結束標記?

3 个解决方案

#1


7  

You can modify the dom structure like a string, but you'd have to target the parent element as you can't insert partial elements

您可以像字符串一樣修改dom結構,但是您必須定位父元素,因為您無法插入部分元素

$('.button').click(function () {
    $('.border').each(function () {
        var t = $(this).parent().html();
        var s = t.split('Hello').join('</span>Hello<span class="border">');
        $(this).parent().html(s)
    });
});

FIDDLE

Note that this works with the example, but if the parent has other elements as well, it can cause issues, and I would strongly suggest finding another way to get the result you're looking for other than closing and opening elements in the middle etc.

請注意,這適用於示例,但如果父級也有其他元素,它可能會導致問題,我強烈建議找到另一種方法來獲得您正在尋找的結果,而不是關閉和打開中間的元素等。

EDIT:

Here's another way of doing it, this doesn't affect the parent at all, and is much neater.
It uses outerHTML to get the surrounding tags as well, that way no partial elements are inserted, but both opening and closing tags are part of the strings passed

這是另一種方法,它不會影響父母,而且更加整潔。它使用outerHTML來獲取周圍的標記,這樣就不會插入部分元素,但是開始和結束標記都是傳遞的字符串的一部分

$('.button').click(function () {
    $('.border').each(function () {
        this.outerHTML = this.outerHTML.split('Hello').join('</span>Hello<span class="border">');
    });
});

FIDDLE

or the even neater jQuery version

或者更整潔的jQuery版本

$('.button').click(function () {
    $('.border').prop('outerHTML', function(_, html) {
        return html.split('Hello').join('</span>Hello<span class="border">');
    });
});

FIDDLE

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复