javascript - 更改元素的 className 会导致使用 $(className).each() 无法找到它

标签 javascript jquery html

我有一些 JQuery 代码,可将特定类的所有 HTML 元素转换为文本区域元素。

我的问题:我使用 JQuery(.addClass()) 将元素类从“可更新”更改为“可更新 P”。但是当我去搜索所有具有“可更新”类的元素时(使用函数 $(".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 添加为类?

关于javascript - 更改元素的 className 会导致使用 $(className).each() 无法找到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7523188/

相关文章:

javascript - 如何显示使用变量选择的单选按钮?

javascript - jQ 将事件从单击更改为悬停

jQuery 包含

javascript - 无法获取 2 个文本框的值

JavaScript 二维渲染库 [pixie.js vs three.js]

javascript - 如何使用expressjs连接?

javascript - HTML5 视频播放器 - video.js - Chromium 和 Mozilla Firefox 上视频播放结束时的不同行为

html - 动态填充表格单元格时如何将 div 定位在表格单元格的底部

javascript - 制作点击播放视频的 YouTube 视频标题卡

javascript - jQuery UI 的高亮效果可以应用于表单文本输入吗?