具有数据属性的 HTML Option 元素。是否可行,如果可行,如何使用 jQuery 检索价值?

Kod*_*.Me 6 html jquery

我只是想知道是否有可能在 html 中使用带有 data- 属性的选项元素,如果有可能如何检索这个值。

更加具体。假设我有以下代码:

<select name="areas" id="areas">
    <option value="1" data-lat="12.243" data-lng="32.43242">Area name</option>
    <option value="2" data-lat="14.243" data-lng="34.43242">Area name</option>
    <option value="3" data-lat="16.243" data-lng="36.43242">Area name</option>
    <option value="4" data-lat="18.243" data-lng="38.43242">Area name</option>
</select>
Run Code Online (Sandbox Code Playgroud)

那么,有没有办法通过 jQuery 从所选选项中获取 data-lat 和 data-lng ?

Ber*_*ard 7

是的,这是可能的。可以通过以下方式获取任何属性值:

$('option:selected').attr('data-lng')
Run Code Online (Sandbox Code Playgroud)

并设置:

$('option:selected').attr('data-lng', 1234);
Run Code Online (Sandbox Code Playgroud)


Ori*_*iol 5

使用以下命令设置属性setAttribute

document.getElementById('areas')
    .getElementsByTagName('option')[index]
    .setAttribute('data-lng', 'foo');
Run Code Online (Sandbox Code Playgroud)

使用以下方式获取属性getAttribute

document.getElementById('areas')
    .getElementsByTagName('option')[index]
    .getAttribute('data-lng');
Run Code Online (Sandbox Code Playgroud)

获取和设置:

var el = document.getElementById('areas')
    .getElementsByTagName('option')[index];
el.getAttribute('data-lng');
el.setAttribute('data-lng', 'foo');
Run Code Online (Sandbox Code Playgroud)

注1我使用过document.getElementById('areas').getElementsByTagName('option')[index],因为可能更跨浏览器,但你可以使用

  • document.getElementById('areas').getElementsByTagName('option')[index]
  • document.getElementById('areas').options[index]
  • document.getElementById('areas')[index]

注2我已经使用了setAttributeandgetAttribute因为它们更跨浏览器,但你也可以使用dataset

el.dataset.lng;            // get
el.dataset.lng = 'foo';    // set
Run Code Online (Sandbox Code Playgroud)