[英]How do I get the value of the text input inside a <td> element (Without JQuery)?
如何獲取元素內文本輸入的值?
我有多個ID,所以我先將它們的字符串分配到數組中;
var itemArray = ["regpay", "overtime","absent","nightdiff","ctpa","salary","hdmf","otallowance","others"];
我使用for循環實例化了它們
for (var i = 0; i < itemArray.length; i++)
{
var e = $("<td><input type=\"text\" autocomplete=\"off\" name=\""+itemArray[i]+"\" id=\""+itemArray[i]+"\"/></td>");
var mytest =e.find('#'+itemArray[i]).val();
alert(mytest);
}
錯誤顯示“未定義$”; 如何獲取td元素內的文本框的值
?
我也嘗試過使用:
try
{
var Row = document.getElementById(itemArray[i]);
var Cell = Row.getElementsByTagName("td");
var val = Cell.getElementById(itemArray[i]);
}
但是val變量不返回任何內容,因此我假設td不會顯式地獲取其中的文本框的值。
如果您已經有#ids
的列表,則只需使用document.getElementById
查詢選擇器 :
var ids = [ "regpay", "overtime","absent", "nightdiff", "ctpa", "salary", "hdmf", "otallowance", "others"]; var r = []; ids.forEach(function (id) { r.push(document.getElementById(id).innerHTML); }) alert("text found:" + r);
<p id='regpay'>0</p> <p id='overtime'>1</p> <p id='absent'>2</p> <p id='nightdiff'>3</p> <p id='ctpa'>4</p> <p id='salary'>5</p> <p id='hdmf'>6</p> <p id='otallowance'>7</p> <p id='others'>8</p>
(我在這里使用<p
> s,因為我不想創建整個表結構,但是上面的內容也可以用於<td>
s。如果上面的id指向輸入框,則應使用document.getElementById(id).value
。這方面您的問題不清楚。
您不需要jQuery(因此不需要$
)。
您可以連接字符串而不使用jQuery,如下所示:
"<td><input type=\"text\" autocomplete=\"off\" name=\"" + itemArray[i] + "\" id=\"" + itemArray[i] + "\"/></td>"
此外, for
語句中的變量大寫( I
),而稍后使用的變量則不大寫( i
)。 如果您希望代碼正常工作,請確保它們是相同的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.