我有一些JQuery代碼可以將特定類的所有HTML元素從textarea元素轉換爲&。我使用JQuery(.addClass())將元素類從「updatable」更改爲「updatable P」。我使用JQuery(.addClass())將元素類從「可更新」更改爲「可更新P」。但是,當我去搜索所有具有「可更新」類的元素(使用函數$(「。updatable」)。each())時,它找不到任何元素,當它應該找到3時。
我做錯了什麼做到這一點?看起來,在我更改元素classI後,我無法再通過它的類(使用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>
+1:你只是用這個答案擊敗了我。 – nnnnnn