简体   繁体   中英

Jquery ReplaceWith() using conditional function not behaving as I expected

I'm learning jQuery and I'm using an online tutorial. I'm at the portion where we are learning about the replaceWith() function and how it can use another function as it's return results. Looking at the teachers code I don't understand how it's working.

jQuery

$("document").ready(function () {
    $("#example p").replaceWith(replacementFn);
    function replacementFn() {
        if ($(this).text().indexOf("1") != -1) {
            return "<p>This is paragraph uno</p>";
        }
    }
});

HTML

<div id="example">
    <p class="a">This is paragraph 1</p>
    <p id="para1">This is paragraph 2</p>
    <p class="b">This is paragraph 3</p>
    <p id="para4" lang="en-us">This is paragraph 4</p>
    <p id="para5" lang="en-gb">This is paragraph 5</p>
</div>

As the code is it works like I was shown. One paragraph is replaced with the "This is paragraph uno" . But once I change the indexOf("1") to indexOf("6") everything in the Example div gets wiped out. What I don't understand is why when at least one paragraph meets the check everything works fine. But once none of them meet the check everything gets wiped out.

Why doesn't the original code wipe everything but the paragraph that matches the check?

If would appear that this line in the jQuery source is the cause. If the replacement function returns something unusable for all items in the set, then the entire set is deleted from the DOM:

// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();

I would say that this conditional replacement that you are using seems like a loophole of some sort, and it is not documented in the jQuery documentation.

I suggest filtering the items you want to replace before carrying out the replacement:

$("#example p").filter(pickItems).replaceWith(replacementFn);

function pickItems() {
    return $(this).text().indexOf("1") !== -1;
} 

function replacementFn() {
    return "<p>This is paragraph uno</p>";
}

Alternatively, you can conditionally return the new content, or the original items when not replacing them:

 $(function () { $("#example p").replaceWith(replacementFn); function replacementFn() { if ($(this).text().indexOf("6") !== -1) { return "<p>This is paragraph uno</p>"; } return this; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div id="example"> <p class="a">This is paragraph 1</p> <p id="para1">This is paragraph 2</p> <p class="b">This is paragraph 3</p> <p id="para4" lang="en-us">This is paragraph 4</p> <p id="para5" lang="en-gb">This is paragraph 5</p> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM