本文介绍了如何在jQuery中设置没有值的HTML属性(例如选中,选中,禁用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,使用HTML处理时,需要设置DOM元素的属性而不使用任何值,例如在此处查看selected参数:

<select id="auto-makers">
  ...
  <option value="fiat" selected>FIAT</option>
  <option value="ford">FORD Motor Company</option>
  <option value="gm">General Motors</option>
  ...
</select>

HTML文档中的这种属性并不罕见.例如,以下是可能的属性列表:

  • checked;
  • selected;
  • required;
  • multiple;
  • disabled;
  • .

如何在运行时使用Javascript和/或jQuery设置没有值的属性?

解决方案

按照您的示例,假设您拥有

<select id="auto-makers">
  ...
  <option value="fiat">FIAT</option>
  <option value="ford">FORD Motor Company</option>
  <option value="gm">General Motors</option>
  ...
</select>

,并且您要将selected属性添加到<option>,例如value="fiat".因此,使用纯Javascript ,您可以使用setAttribute方法:

var select = document.getElementsById('auto-makers');
for (var i=0; i<select.options.length; i++){
   if (select.options[i].value=="fiat"){
     select.options[i].setAttribute('selected','');
     break;
   }
}

在使用 jQuery 时,您可以简单地使用attr方法:

$('#auto-makers').find('option[value="fiat"]').attr('selected','');

在两种情况下,都将空字符串作为属性的值传递.

您可以在提供更改后查看相关的HTML代码,以验证输出是否是所需的.

最后,请注意,类似的问题是:"设置没有值的属性"./p>

Sometimes, when handling with HTML, it is required to set an attribute of a DOM element without using any value, e.g. see the selected parameter here:

<select id="auto-makers">
  ...
  <option value="fiat" selected>FIAT</option>
  <option value="ford">FORD Motor Company</option>
  <option value="gm">General Motors</option>
  ...
</select>

This kind of attributes in HTML documents are a not rare. For instance, here follows a list of possible attributes:

  • checked;
  • selected;
  • required;
  • multiple;
  • disabled;
  • etc.

How can I set a property with no value at runtime using Javascript and/or jQuery?

解决方案

Following your example, suppose that you have

<select id="auto-makers">
  ...
  <option value="fiat">FIAT</option>
  <option value="ford">FORD Motor Company</option>
  <option value="gm">General Motors</option>
  ...
</select>

and that you want to add the selected attribute to the <option> such that value="fiat". Hence, with pure Javascript you can use setAttribute method:

var select = document.getElementsById('auto-makers');
for (var i=0; i<select.options.length; i++){
   if (select.options[i].value=="fiat"){
     select.options[i].setAttribute('selected','');
     break;
   }
}

while with jQuery you can simply use the attr method:

$('#auto-makers').find('option[value="fiat"]').attr('selected','');

In both cases, an empty string is passed as value for the attribute.

You can verify that the output is the one desired by looking at the related HTML code just after the changes you provided.

Finally, notice that a similar question is: "Set attribute without value".

这篇关于如何在jQuery中设置没有值的HTML属性(例如选中,选中,禁用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:15