改变一个元素的className会导致使用$(className).each()无法找到它

Changing a elements className makes it unfindable using $(className).each()

本文关键字:className each 一个 元素 改变      更新时间:2023-09-26

我有一些JQuery代码,将特定类的所有HTML元素转换为&从textarea元素

我的问题:我使用JQuery(. addclass())将元素类从"updatable"更改为"updatable p"。但是,当我去搜索所有具有"updatable"类的元素(使用函数$(".updatable").each())时,它没有找到任何元素,而应该找到3。

我做错了什么让这一切发生?似乎在我改变一个元素的类之后,我无法通过它的类(使用JQuery)再次识别/找到该元素。

<html>
<head>
    <script type="text/javascript" src="jquery-1.6.4.js"></script>
    <script type="text/javascript">
    <!--
        var STATE = 1;
        function Toggle()
        {
            if (STATE==1) { convertToUpdatable(); STATE = 0; }
            else          { convertToStatic();    STATE = 1; }
        }
        function getTitleName( ele )
        {
            try        { return ele.className.split(" ")[1]; }
            catch (ex) { return "undefined"; }
        }
        function convertToUpdatable()
        {
            // Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements
            //       and store their HTML element type in the class attribute
            // EG: Before: <p class="updatable Paragraph1"/> Hello this is some text 1 </p>
            //     After : <p class='updatableElementTitle'>Paragraph1</p><textarea class="updatable Paragraph1 p"/> Hello this is some text 1 </textarea>
            $(".updatable").each(function()
                {
                    var title = getTitleName( this );
                    $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea>"+$(this).text() +"</textarea>");
                    $(this).addClass( this.nodeName );
                    alert( this.className );
                });
        }
        function convertToStatic()
        {
            // Post: Find all HTML elements (with the class 'updatable'), check to see if they are part of another class aswell
            //       (which will be their original HTML element type) & convert the element back to that original HTML element type
            // PROBLEM OCCURS HERE: after I have changed an elements className in the convertToUpdatable() I can no
            //                      longer find any HTML elements that have the className updatable using $(".updatable").each()
            $(".updatable").each(function()
                {
                    alert("Loop");
                    // Determine elements original HTML(node) type
                    try
                    {
                        var type = this.className.split(" ");
                        type     = (type[ type.length-1 ]).toLowerCase();
                        alert(type);
                    }
                    catch (ex) { alert("Updatable element had no type defined in class attribute"); return; }
                    // Convert element back to original HTML type
                    $(this).replaceWith( type +$(this).text() + type );
                    // Remove elements type from its className (remove " P" from "updatable Paragraph1 P")
                    $(this).removeClass( type ); 
                    alert( this.className );
                });
            // Delete all elements with the class 'updatableElementTitle'
            $(".updatableElementTitle").remove();
        }
    -->
    </script>
</head>
<body>
    <p class="updatable Paragraph1"/> Hello this is some text 1 </p>
    <b class="updatable Paragraph2"/> Hello this is some text 2 </b>
    <i class="updatable Paragraph3"/> Hello this is some text 3 </i>
    <input id="MyButton" type="button" value="Click me!" onclick="Toggle();" />
</body>
</html>

.replaceWith()破坏现有元素。因此,在循环中完成replaceWith()之后,您不能再使用this,因为该DOM元素不再是文档中的元素(它是已被删除的旧元素,一旦函数退出就会被垃圾收集)。

由于您正在为新标记指定HTML,我建议您只需将新类名称放在传递给replaceWith()的HTML中。此外,必须检查className的警告正在检查旧的DOM元素,而不是新的DOM元素。请记住,this指向旧的DOM名称,而不是您所替换的名称。

你可以这样做:

        $(".updatable").each(function()
            {
                var title = getTitleName( this );
                $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea>"+$(this).text() +"</textarea>");
                $(this).addClass( this.nodeName );
                alert( this.className );
            });
    }

:

        $(".updatable").each(function()
            {
                var title = getTitleName( this );
                $(this).replaceWith("<p class='updatableElementTitle " + this.nodeName + "'>" + title + "</p><textarea>"+$(this).text() +"</textarea>");
            });
    }

虽然,我不明白你为什么要添加nodeName作为一个类?

您正在使用replaceWith(根据规范)完全删除所有内容并用新内容替换它。在您替换了内容之后,就没有updatable类的节点了,所以您再也找不到它们了。

尝试用$(this).addClass('updatable');代替$(this).addClass( this.nodeName );