[英]Change input value or add a new input if it doesn't exist
背景:我需要附加某些數據才能發布; 類似於jQuery的ajaxSetup
為異步請求執行的操作,除了我需要它用於本機表單提交。
我需要能夠在提交之前向表單添加幾個表單字段,但我想確保我不添加重復字段以防它們已經存在(即原始提交因驗證失敗或某事)。
起初我覺得這樣的事情會很好而且連貫:
$("form").live("submit", function ()
{
var $this = $(this);
($this.find('#stuff') ||
$this.append('<input type="hidden" id="stuff" name="stuff" />'))
.val('some value');
// carry on with the native submit
// this is actually correct, as opposed to $this.submit()
// which would create a loop
this.submit();
});
意思是尋找#stuff
,如果找不到它,則將其值設置為“某個值” 。 但是因為.find()
的結果實際上是一個jQuery包裝器,它將被隱式轉換為一個true
含義,即使找不到匹配的元素,也永遠不會執行.append()
代碼。
有沒有一種很好的方法可以解決整個“尋找元素並創建它,如果它還不存在”的情況?
將$this.find('#stuff')
更改$this.find('#stuff').length
如果你想在一個陳述中能夠做到這一切,那么你可以做到
(
($this.find('#stuff').length && $this.find('#stuff')) ||
$('<input type="hidden" id="stuff" name="stuff" />').appendTo($this)
).val('some val');
為了保持檢查邏輯可讀,可以擴展條件:
if ($this.find('#stuff').length) {
$this.find('#stuff').val('some val');
} else {
$this.append('<input type="hidden" id="stuff'" name="stuff" value="some val" />');
}
或者,人們可以刪除並重新添加元素...我知道,“dom操作很昂貴”但是如果有幾個字段要操作它就這么漂亮了:
$this.find('#stuff', '#stuff2', ...).remove()
.append('<input type="hidden" id="stuff" name="stuff" value="some val" />...');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.