[英]How To Access Dynamically Created Page Elements with jQuery (not events, ELEMENTS!)
我在頁面上有幾個動態創建的元素,我想使用jQuery將內容發布到另一個頁面。 問題是,創建的元素無法通過jQuery訪問(只有頁面上存在的元素可以使用$(#myElementID)訪問。我已經看到數百個帖子使用live()和on()函數進行訪問EVENTS,但無法訪問動態創建的ELEMENTS的任何屬性,值,innerHTML等。這是不可能用jQuery做的?
$('#btnParseTable').click(function () {
var tblCustomPattern = $("#tblCustomPattern").innerHTML;
//This test alert yields "" because tblCustomPattern is undefined - yet FireBug clearly shows the table exists!
alert(tblCustomPattern);
var postData = { "method": "ParseTable", "tbl": tblCustomPattern };
$.post("tiler.aspx", postData, function (data) {
$("#test").html(data); //for testing
});
});
如果jQuery不支持,可以用JavaScript完成,還是不能回發非“INPUT”元素的信息?
此測試警報產生“”因為tblCustomPattern未定義 - 但FireBug清楚地顯示該表存在!
您可以在將動態創建的元素添加到DOM
后對其進行評估。 tblCustomPattern undefined
因為jQuery
對象沒有屬性innerHTML
您需要DOM
元素才能使用innerHTML
但選擇器將返回jQuery對象。 您可以使用indexer []
或[get()][1]
從jQuery對象獲取html元素。 它是zero-based
索引,您將獲得零index
第一個元素。
var tblCustomPattern = $("#tblCustomPattern")[0].innerHTML;
或者,使用.get()
var tblCustomPattern = $("#tblCustomPattern").get(0).innerHTML;
或使用html()
var tblCustomPattern = $("#tblCustomPattern").html();
在這部分代碼中,您遇到了一個問題:
$("#tblCustomPattern").innerHTML;
問題是$("#tblCustomPattern")
是一個jQuery對象。 它不是DOM對象。 jQuery對象沒有屬性.innerHTML
。
因此,要解決您的問題,您有以下幾種選擇:
.innerHTML
屬性。 .html()
方法將jQuery方法用於相同的功能。 所以,任何這些都可行:
// get the first DOM object from the jQuery object
// two different methods for doing that
var tblCustomPattern = $("#tblCustomPattern")[0].innerHTML;
var tblCustomPattern = $("#tblCustomPattern").get(0).innerHTML;
// use the jQuery method to get the HTML
var tblCustomPattern = $("#tblCustomPattern").html();
// use plain JS - fastest option
var tblCustomPattern = document.getElementById("tblCustomPattern").innerHTML;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.