我希望克隆一個元素(#clone)的innerhtml並將其插入到另一個元素(#newLocation)中。複製HTML並保留事件
使用clone()的問題是,我將首先刪除#newLocation中的當前元素(如果有),然後遍歷#clone中的每個元素並將其追加到#newLocation。不是世界末日,而是希望更簡單的方式。
相反,我想我會使用HTML()。由於這不會保留事件,因此我必須委派甚至使用ON。我曾認爲這項工作有效,但事實並非如此。
任何建議我做錯了什麼?另外,即使我可以使用html()解決方案,使用clone()解決方案會更有效率嗎?
謝謝
編輯。剛剛寫了我的第一個插件.http://jsfiddle.net/Wnr65/似乎工作。好主意使用?當然可以寫得更好。由於
$(document).ready(function(){
$("#cloneIt").click(function(){$('#newLocation').cloneInnerHtml('clone').css('color', 'red');});
$("#clone a").click(function(){alert("click");});
$("#clone select").change(function(){alert("change");});
});
(function($){
$.fn.cloneInnerHtml = function(id) {
this.empty();
var $t=this;
$('#'+id).each(function() {$t.append($(this).clone(true));});
return this;
};
})(jQuery);
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Clone INNERHTML</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" language="javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#cloneIt").click(function(){$('#newLocation').html($('#clone').html());});
//Only works on original clone
$("#clone a").on("click", function(){alert("click");});
$("#clone select").on("change", function(){alert("change");});
//Doesn't work at all
$("#newLocation a").on("click", function(){alert("click");});
$("#newLocation select").on("change", function(){alert("change");});
});
</script>
</head>
<body>
<input type="button" value="Clone it" id="cloneIt" />
<p>Original clone is shown below</p>
<div id="clone">
<a href="#">Click Me</a>
<select><option>Hello</option><option>Goodby</option></select>
</div>
<hr />
<p>Insert new clones below.</p>
<div id="newLocation">
<p class="someOldElement">someOldElement</p>
</div>
</body>
</html>
一起復制可以創建[jsfiddle.net](HTTP:/ /jsfiddle.net)? – Jakub 2012-04-25 14:16:01
你想要做什麼?複製元素?或者移動元素? – pomeh 2012-04-25 14:31:46
@Jakup http://jsfiddle.net/t8Knk/ – user1032531 2012-04-25 14:50:43