簡體   English   中英

jQuery text() 和 val() 返回 null

[英]jQuery text() and val() returning null

編輯:似乎我沒有在我的 textarea 上使用“id”,所以問題已經解決,但我仍然遇到一些 text() 問題

var e = $('textarea#cost-'+i).val(); // e = 1 (for first iteration)
alert($('p#subtotal-'+i).text()); // alert 'subtotal' which is the text in my p#subtotal-1
$('p#subtotal-'+i).text().replaceWith(e); // <- this is the problem, i think
alert($('p#subtotal-'+i).text()); // no alert box at all

這次我確保他們都有身份證。


下面的代碼會生成一個沒有任何內容的警報框。 如果我將其更改為 val() 它會顯示“未定義”


$('textarea.costbox').live('blur',function() {
for(var i in items) {
alert('iteration '+i);
alert('textarea#cost-'+i);
var e = $('textarea#cost-'+i).text();
alert('cost '+e);
}
});

<textarea name="cost-1" class="costbox"></textarea>

此代碼的想法是在值更改時更新小計。 這是拼圖的最后一塊。

當我在 chrome 中檢查時,所有 HTML 看起來都很正常。 我的代碼的所有 rest 工作正常。

這應該與基於最近的 HTML5Boilerplate 的modernizer1.7 和 jQuery1.5.1 一起運行。

這是相同基本事物的另一個示例 - http://jsbin.com/obeho5/3/edit

它可能很簡單,但我已經被困在這里幾個小時了,看不到它。

[如果它不是明顯和簡單的,我可以發布更多代碼]

#用於通過 ID 獲取,您的元素沒有 ID,只是一個名稱。

添加一個 ID 或使用這個:

'textarea[name="cost-'+i+'"]'

的示例中沒有包含 jQuery 。 使用.val()可以正常工作: http://jsbin.com/obeho5/4/edit

注意:關於您在問題中發布的代碼,其他人是正確的,但您在演示中的標記不同。 在演示中,元素具有 ID。

$('textarea#cost-'+i).text();

正在尋找一個帶有ID的 textarea ,你已經給它一個名字,你需要做:

$('textarea[name="cost-' + i +'"]').text();

編輯:對於您更新的問題:

$('p#subtotal-'+i).text().replaceWith(e); 

應該

$('p#subtotal-'+i).text(e);

您無需擔心replaceWith,您只需將新文本添加為方法的參數即可。

暫無
暫無

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

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