使用jQuery重置字段

resetting fields with jQuery

本文关键字:字段 jQuery 使用      更新时间:2024-06-12

我正在尝试重置分部中的字段(选择和文本框)。以下是我目前所拥有的:

var $inputs = $('#StudentTable :select');
$inputs.each(function () { 
  if ($(this).name = "TeachingAsstSelect") { 
    $('select[name="TeachingAsstSelect"]').each(function () { 
      $(this).text(""); 
    }) 
  } 
  else { 
    $(this).val("Select");
  } 
});

此处"TeachingAsstSelect"被清除,但其他选择不会重置。我是不是错过了什么?更重要的是,我这样做对吗?

如果要测试字符串的相等性,则应使用=====。请参阅此处的表格了解更多信息:JavaScript比较中应该使用哪个等于运算符(==vs===)?

此外,正如@Raminson所建议的,请尝试使用attr()方法。

if ($(this).attr('name') == "TeachingAsstSelect") { 

或者更好的是,像这样嵌套两次.each()可能不如其他解决方案执行得好。

我还注意到,您正在if条件中测试名称,然后使用jquery选择器在[name="TeachingAsstSelect"]上再次匹配。像这样简化怎么样:

var $teachingAsstInputs = $('#StudentTable :select[name="TeachingAsstSelect"]');
$($teachingAsstInputs).text(""); 
var $otherInputs = $('#StudentTable :select').not('[name="TeachingAsstSelect"]');
$($otherInputs).val("Select"); 

对于jQuery对象,应该使用attr()方法,name是DOM元素属性之一。

更改此项:

  if ($(this).name = "TeachingAsstSelect") { 

至:

  if ($(this).attr('name') == "TeachingAsstSelect") { 

还要注意,为了进行比较,您应该使用==运算符,目前您正在设置该值。