簡體   English   中英

jQuery:選擇新添加的DOM節點的最佳方法是什么?

[英]Jquery: What is the best way to select the newly added DOM node?

我有一個外部模板文件,該文件的結構是單擊按鈕時動態添加到表中的。 當以這種方式添加新表行時,我需要在此新添加的代碼段上調用回調。

我想知道,選擇此新代碼的最佳方法是什么。 它有一個ID,因此編寫其他選擇器不會有問題,但是我想知道是否有更簡便的方法來選擇它。

這是一段代碼:

$rightSpot.append(app.renderTemplate('temp/product', tplData ));

編輯:這對我有效,但也許有更好的方法:

$newProduct = $rightSpot.find('tr').last().find('textarea');

我會考慮使用react.js。 使用react的好處是它可以與虛擬DOM一起使用,因此在回調可用之前,您將不會依賴要呈現的物理DOM。

http://facebook.github.io/react/

我不知道這是否是最好的方法,但是您可以執行以下操作-

 $("#giveitafriend").click(function() { $("#ab").append($("<span>") .text("I'm here too!") .css("color", "red") ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="ab"> <span>On My Own</span> </div> <button id="giveitafriend">Give it a Friend</button> 

假設您的renderTemplate函數返回HTML元素,也許您可​​以按如下方式訪問新元素

var newElement = app.renderTemplate('temp/product', tplData ); 
$rightSpot.append(newElement);
console.log($(newElement).attr('id'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM