我試圖根據當前內容替換一系列'for'屬性的標籤。如何替換jQuery中一組元素的部分屬性值?
該應用程序正在使用AJAX將項目添加到發票而不刷新頁面。在接收到成功項目添加的通知後,我的腳本應該替換表單中'for'屬性以'-new'結尾的所有標籤,並使用相同的屬性減去'-new'並添加(' - '+ itemValue),其中itemValue是已添加的發票項目的項目標識。
我知道如何選擇所有我想一次更改標籤:
jQuery('label[for$=new]')
我知道如何讓自己「的」屬性:
jQuery('label[for$=new]').attr('for')
我嘗試了JavaScript的替代方法:
jQuery('label[for$=new]').attr('for').replace(/-new/,itemValue)
但是,似乎選擇每個標籤的'for'屬性,替換文本,並通過r因爲我不知道如何識別具有我想要替換的'for'屬性的標籤。
這是一些示例HTML:
<form id="InvoiceItemsForm-1" action="<?=$_SERVER['PHP_SELF'];?>" method="post" name="InvoiceItemsForm-1" onsubmit="return false">
<div id="InvoiceItem-new-1" class="InvoiceItem">
<label for="InvoiceItemNumber-new">New Invoice Item Number: </label>
<input id="InvoiceItemNumber-new" class="InvoiceItemNumber" type="text" value="" name="InvoiceItemNumber-new">
<label for="InvoiceItemDescription-new">Item Description: </label>
<input id="InvoiceItemDescription-new" class="InvoiceItemDescription" type="text" value="" name="InvoiceItemDescription-new">
<label for="InvoiceItemAmount-new">Item Amount: </label>
<input id="InvoiceItemAmount-new" class="InvoiceItemAmount" type="text" value="" name="InvoiceItemAmount-new">
<input id="addInvoiceItem-1" width="25" type="image" height="25" src="/payapp/images/greenplus.th.png" alt="Add New Invoice Item" onclick="addInvoiceItemButtonPushed(this)" value="invoiceItem">
</div>
<button id="CloseInvoice-1" onclick="closeInvoice(this)" type="button">Close Invoice</button>
</form>
一旦我得到這個工作,我要全部更換爲IDS所有輸入。同樣的問題。我想象的解決方案看起來像這樣:
jQuery('input[id$=new]').attr('id').replace(/-new/,itemValue)
我只是無法弄清楚這個語法。
這是我追求的最佳答案正如所問。所有3個答案都是解決問題的有效方法。 – chriv 2012-04-28 16:44:30