本机将HTML选择元素设置为其默认值 [英] Natively set HTML select element to its default value

查看:122
本文介绍了本机将HTML选择元素设置为其默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个select元素,用户改变选择。后来我想以编程方式将select元素更改回默认值。什么是最好的方法来做到这一点?我正在寻找一种方法来实现本地化,无需JQuery。



例如,如果select为:

 < select id ='select'> 

用户将选择更改为Two,但后来我想将其更改回默认值One的值如何做到这一点?

解决方案

如果您明白属性不同于属性。属性(通常)不会改变,但属性可以。 选定的属性将始终保持原来的HTML状态,而选定的属性将取决于发生了什么 $ b

因此,您可以根据选定元素选择原始选定元素 属性,然后设置它的选中 属性

  document.querySelector('option [selected]')。selected = true; 

jsFiddle展示了这一点。 请注意,这需要支持 querySelector 的modern-ish浏览器。这些是他们中的大多数,但是一些旧的浏览器不会。如果这是一个问题,你将不得不使用 hasAttribute('selected')来查找元素。


I have a select element and the user changes the selection. Later I want to programmatically change the select element back to its default value. What's the best way to do this? I am looking for a way to do this natively, without JQuery.

For example if the select is:

<select id='select'>
  <option value='one' selected=true>One</option>
  <option value='two'>Two</option>
  <option value='three'>Three</option>
</select>

And the user changes the selection to "Two" but later I want to change it back to the default value of "One" how would I do this?

解决方案

This is not difficult to do if you understand that properties are different from attributes. Attributes (generally) don't change, but properties do. The selected attribute will always remain as it is in the original HTML, while the selected property will depend on what's happened to the element in the lifetime of the page.

So you can select the original selected element based on its selected attribute and then set its selected property.

document.querySelector('option[selected]').selected = true;

jsFiddle demonstrating this.

Note that this requires a modern-ish browser that supports querySelector. This is most of them, these days, but some old browsers won't. If this is a problem, you will have to find the element using hasAttribute('selected').

这篇关于本机将HTML选择元素设置为其默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆