背景:我需要附加某些数据才能发布;类似于 jQueryajaxSetup
为异步请求所做的,除了我需要它来提交本地表单。
我需要能够在提交之前向表单添加几个表单字段,但我想确保我不会添加重复的字段以防它们已经存在(即原始提交由于验证或其他原因而失败)。
起初我认为这样的事情会很好而且连贯:
$("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
,如果没有找到就创建它,然后将它的值设置为 "some value"。但是因为 的结果.find()
实际上是一个 jQuery 包装器,所以它会被隐式转换为true
即使没有找到匹配的元素,.append()
也永远不会执行代码的含义。
有没有一种很好的方法来解决整个“寻找一个元素并在它不存在的情况下创建它”场景?