如何实现与元素交互的功能?

时间:2016-10-27 09:39:32

标签: javascript jquery html css

在这里,我需要为那些 选项 元素设置所选属性,其中相应的 li 选择了班级。值由 li 中的属性 data-input-value 选项中的值属性

<div class="wrapper">
        <select name="name">
          <option value="val1">name1</option>
          <option value="val2">name2</option>
        </select>
        <ul data-input-name="name">
          <li data-input-value="val1" class="disabled">name1</li>
          <li data-input-value="val2" class="enabled selected">name2</li>
        </ul>
      </div>

1 个答案:

答案 0 :(得分:2)

&#13;
&#13;
$('select[name="name"] option').each(function() {   
  if ($('li[data-input-value="' + $(this).val() + '"]').hasClass('selected')) {
    $(this).prop('selected', true);   
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
  <select name="name">
    <option value="val1">name1</option>
    <option value="val2">name2</option>
  </select>
  <ul data-input-name="name">
    <li data-input-value="val1" class="disabled">name1</li>
    <li data-input-value="val2" class="enabled selected">name2</li>
  </ul>
</div>
&#13;
&#13;
&#13;