Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更改输入值或添加新的输入(如果没有';不存在_Javascript_Jquery - Fatal编程技术网

Javascript 更改输入值或添加新的输入(如果没有';不存在

Javascript 更改输入值或添加新的输入(如果没有';不存在,javascript,jquery,Javascript,Jquery,背景:我需要在帖子中添加某些数据;类似于jQuery对异步请求所做的,只是我需要它用于本机表单提交 在提交表单之前,我需要能够向表单中添加几个表单字段,但我希望确保不会添加重复的字段,以防它们已经存在(例如,由于验证或其他原因,原始提交失败) 起初,我认为这样做会很好,也很连贯: $("form").live("submit", function () { var $this = $(this); ($this.find('#stuff') || $this.appe

背景:我需要在帖子中添加某些数据;类似于jQuery对异步请求所做的,只是我需要它用于本机表单提交

在提交表单之前,我需要能够向表单中添加几个表单字段,但我希望确保不会添加重复的字段,以防它们已经存在(例如,由于验证或其他原因,原始提交失败)

起初,我认为这样做会很好,也很连贯:

$("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();
});
$(“表单”).live(“提交”,函数()
{
var$this=$(this);
($this.find('stuff'))||
$this.append(“”))
.val(“某些值”);
//继续进行本地提交
//这实际上是正确的,与$this.submit()相反
//这将创建一个循环
这个。提交();
});
意思是查找
#stuff
,如果找不到,则创建它,然后将其值设置为“some value”。但是,由于
.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');
(
($this.find('stuff').length&$this.find('stuff'))|
$('').appendTo($this)
).val(“某个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" />');
}
if($this.find('#stuff').length){
$this.find('stuff').val('some val');
}否则{
$this.append(“”);
}
或者,可以删除并重新添加元素。。。我知道,“dom操作很昂贵”,但如果有几个字段需要操作,那么这样做就更漂亮了:

$this.find('#stuff', '#stuff2', ...).remove()
  .append('<input type="hidden" id="stuff" name="stuff" value="some val" />...');
$this.find('stuff'、'stuff 2'、…).remove()
。附加(“…”);

mmm。。。我将无法
($this.find(“#stuff”).length | |/*add#stuff*/).val('new value')
thogh,我会吗?几乎
.val()
在追加输入时似乎不起作用。如果没有别的,这说服了我使用不那么晦涩的If-else:)只是为了好玩。它仍然可以通过反转选择来工作,即
。|124;$(“”).appendTo($this)
您确实丢失了与元素相关的任何/所有事件though@Josh:是的,但在我的案例中没有问题/对于隐藏输入,我的评论仅供参考。我想您发布了一个适合您的解决方案:)