2012-03-08 74 views
4

單擊我正在複製div。我希望改變一些html,然後追加。jQuery在克隆上更改html

我試過以下,它會克隆和追加,但我似乎不能改變HTML。不知道處理它的最佳方式是什麼,我相信我錯了。

感謝

var htmlStr = $(this).parents(".listingContainer").first(); 
$htmlStr.find(".saveCompareShow").remove() 
$(htmlStr).clone().appendTo('.compareWrapper');       
+0

你是否試圖通過某種可能不再唯一標識元素的id屬性來編輯克隆的html,現在它的克隆呢? – 2012-03-08 15:40:26

+0

對不起應該更清楚了,.saveCompareShow是一個與外部複製的div,它在那裏沒問題。我只是使用不正確的語法來找到它。在firebug中的錯誤是$ htmlStr沒有定義 – 2012-03-08 15:44:31

+2

Heads-up:你在第二行引用一個未定義的變量。 – shaunsantacruz 2012-03-08 15:45:58

回答

7

一旦克隆就好像你想改變一個DOM元素的DOM元素,你應該把它沒有被克隆。你只需使用你的變量而不是選擇器。

假設你有HTML這樣的:

​<div class='listingContainer'> 
    <div class='listing'> 
     Something 
    </div> 
    <div class='listing'> 
     Another something 
    </div> 
</div> 

您可以克隆listingContainer DIV的內容並追加到compareWrapper DIV前更改內容。下面的JavaScript顯示了一個簡單的例子:

$(document).ready(function() { 
    $('.listing').click(function() { 
     var $htmlStr = $(this).parents(".listingContainer").first(); 
     $htmlStr.clone().find('.listing').html('<li>Cloned</li>').appendTo('.compareWrapper'); 
    }); 
}); 

我還貼了的jsfiddle所以你可以看到它的工作:http://jsfiddle.net/hkBMK/

0

讓你的變量htmlStr實際上是一個因素,而不是一個字符串。但沒關係。我認爲你需要做的這第二行:

htmlStr.remove(".saveCompareShow"); 

如果我看到正確地將,你試圖刪除從htmlStr元素的類「.saveCompareShow」元素。是對的嗎?

**編輯**

試試這個更換兩線2和3

$(htmlStr).clone().remove(".saveCompareShow").appendTo('.compareWrapper'); 
+0

我曾試過,但它不起作用。我看到你使用的是htmlStr而不是我的$ htmlStr,但它確實有效,但是它從原始和克隆中移除了類 – 2012-03-08 15:47:57

+0

@KeithPower - 請參閱我的編輯,是的,我給出的原始解決方案將從原始元素中移除該元素。 – 2012-03-08 16:22:00

1

克隆後,你可以把對象就好像它是HTML已經在dom。

例如 - HTML頁面上:

<div id="cloneHere"></div> 
<div class="well" id="buildInfoTemplate"> 
    <form> 
     <fieldset> 
      <legend></legend> 
      <label></label> 
      <input type="text" placeholder="Type something…"> 
      <span class="help-block">Example block-level help text here.</span> 

      <button class="btn">Save</button> 
     </fieldset> 
    </form> 
</div> 

比方說,你想改變的幫助塊文本:

var template = $('#buildInfoTemplate').clone().removeAttr('id'); 
$('.help-block',template).html('hi there ryan'); 
$('#cloneHere').append(template); 

,你會得到:

<div id="cloneHere"> 
    <div class="well"> 
    <form> 
     <fieldset> 
      <legend></legend> 
      <label></label> 
      <input type="text" placeholder="Type something…"> 
      <span class="help-block">hi there ryan</span> 

      <button class="btn">Save</button> 
     </fieldset> 
    </form> 
    </div> 
</div>