有没有更干净的方法来编写这些jQuery行?
有没有更干净的方法来写这些行有没有更干净的方法来编写这些jQuery行?,jquery,Jquery,有没有更干净的方法来写这些行 $("input:text").each(function() { if ($(this).val() !== "") $(this).show().prev().addClass('highlighted').parent().parent().prev().prop('checked', true); }); 编辑:一些额外的背景信息 这是关于一项调查,当转到下一个问题时,答案将保存在该调查中。在这个特定的问题上,访问
$("input:text").each(function() {
if ($(this).val() !== "")
$(this).show().prev().addClass('highlighted').parent().parent().prev().prop('checked', true);
});
编辑:一些额外的背景信息
这是关于一项调查,当转到下一个问题时,答案将保存在该调查中。在这个特定的问题上,访问者可以选中复选框。但是,最后两个选项是输入字段。对于这两个输入字段,我都制作了假复选框,并使用jQuery使这些复选框看起来功能正常
当您想导航回此问题时,您选中的常规复选框仍将被选中,但假复选框不会被选中。输入字段也会隐藏,即使它们有值
我需要上面的jQuery来确保在输入字段有值时选中假复选框。“突出显示”类用于额外的视觉确认,即您已检查该答案
现在是html。我几乎无法控制这个标记
<input class="fake-check" type="checkbox">
<div class="question-open-question">
<div class="form-item form-type-textfield form-item-situations-other1">
<label for="edit-situations-other1" class="highlighted">Ik wil: </label>
<input type="text" id="edit-situations-other1" name="situations[other1]" value="" size="60" maxlength="128" class="form-text" style="display: inline-block;">
</div>
</div>
伊克威尔:
现在别误会我。上面的jQuery可以工作。我只是想知道一种更简洁的写作方式
因此,当一个输入字段有一个值时,我需要3件事:
-显示该输入字段
-将类添加到标签的步骤
-要选中复选框以使第二个版本正常工作,您必须保存
$(this).prev()
,并在if
周围加括号,因为您要执行多个语句
$("input:text").each(function() {
if ($(this).val() !== "") {
$(this).show();
var prev = $(this).prev();
prev.addClass('highlighted');
prev.parent().parent().prev().prop('checked', true);
}
});
请注意,使用
prev()
和parent()
是一种脆弱的方法,因为对DOM的大多数更改都会破坏JavaScript。您应该用类名标记您试图访问的元素,并使用closest()
和find()
一个建议是将所有内容包装在容器div中,然后使用它,而不是在DOM中上下跳跃:
<div class="my-section">
...
<span class="to-highlight">...</span>
<input class="my-text">
...
<input type="checkbox" class="my-checkbox">
</div>
这样,代码就可以很好地包含在一个元素中。它不太可能因HTML结构更改而中断,并且不会干扰其范围之外的元素。我通常建议避免使用与HTML结构紧密耦合的函数,例如parent()
和prev()
使用
.end()
返回上一个选择器(在本例中是$(this)
,而不是$(this).prev()
)。目标元素的HTML片段会有所帮助。您可以插入换行符。但是您永远不应该使用.parent().parent()
。通常,最近的
有助于提高代码的可维护性。三行示例中的parent().parent().prev()
与一行不同,因为在三行中,您从此
开始,在一行中从开始(this).prev()
“它不起作用”不是问题陈述。最干净的方式?使用ID。OP试图避免很长的一行。从技术上讲,如果.prev()
返回某个内容,.prev().parent()
和$(this.parent()
是相同的。此代码没有.prev().parent()
。这是从“三行工作”代码中提取的。不幸的是,这与“不作为一行工作”的代码不同。谢谢,但正如我提到的,我希望有一种更干净的方法来做这件事。谢谢你的回答,但我对html标记几乎没有控制权,所以我无法将其全部打包。我将在周一尝试。代替.parent().parent(),我将尝试使用.closest(),比如前面提到的@dystroy
$(".my-section").each(function () {
if ($(".my-text", this).val() !== "") {
$(".my-text", this).show();
$(".to-highlight", this).addClass("highlighted");
$(".my-checkbox", this).prop("checked", true);
}
});
$("input:text").each(function() {
var $t=$(this);
if ($t.val() !== "") {
$t.show().prev().addClass('highlighted').end().parent().parent().prev().prop('checked', true);
}
});