如果element包含特定值,则向sibling添加属性

时间:2016-11-08 20:56:14

标签: jquery forms

刚开始使用javascript / jquery

我有以下形式(生成,因此无法控制输出) 并且如果标签包含< em> *< / em>

,则需要使其成为必需品
<div class="product-configure-options-option">
  <label for="product_configure_option_112843">Aantal verpakkingen links: <em>*</em></label>
  <select name="option[112843]" id="product_configure_option_112843">
    <option value="467619" selected="selected">Geen</option>
    <option value="467631">1</option>      
    <option value="467623">5</option>

  </select>
  <div class="product-configure-clear"></div>
</div>

我尝试过以下代码。 因此,如果div包含一个包含em的标签,请找到最接近的select并添加所需的属性。

$( "product-configure-options-option label" ).has( "em" )(function() {
 $(this).find('select').prop('required',true);
});

我做错了什么?

2 个答案:

答案 0 :(得分:1)

  1. 如果您正在寻找课程,请在其前面添加.
  2. JQuery选择器返回一个对象,你不能调用一个匿名的 像这样的对象的方法。
  3. .find()正在寻找其他元素中的元素,使用 而是.next()
  4. &#13;
    &#13;
    var labelsWithEm = $(".product-configure-options-option label").has("em"); // find all relevant items 
    
    labelsWithEm.each(function() { // iterate the items
      $(this).next('select').prop('required', true); // find the next sibling that is select, and add the prop
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="product-configure-options-option">
      <label for="product_configure_option_112843">Aantal verpakkingen links: <em>*</em>
      </label>
      <select name="option[112843]" id="product_configure_option_112843">
        <option value="467619" selected="selected">Geen</option>
        <option value="467631">1</option>
        <option value="467623">5</option>
    
      </select>
      <div class="product-configure-clear"></div>
    </div>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

您的代码存在两个问题:

  1. $( "product-configure-options-option ...查找名为“product-configure-options-option”的标记的元素。您想要一个具有的元素,您可以通过预先设置一个句点来获得:$( ".product-configure-options-option ...

  2. $(this).find('select')查找标签的的SELECT元素。你想要它的兄弟,你可以用$(this).next('select')获得它。