2016-11-08 73 views
0

剛開始使用JavaScript/jQuery的添加屬性兄弟如果元素包含特定值

我有follwing形式(產生的,所以就沒有輸出控制) 並希望把它要求如果標籤包含< 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的標籤,找到最接近的選擇並添加所需的屬性。

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

我在做什麼錯?

回答

1
  1. 如果您正在尋找一門課程,請在其之前添加.
  2. JQuery選擇器返回一個對象,你不能用這樣的對象調用一個匿名的 方法。
  3. .find()正在尋找其他元素內的元素,請使用 .next()來代替。

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 
 
});
<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>

0

有兩個問題與您的代碼:

  1. $("product-configure-options-option ...查找與標籤稱爲「產品配置選項,選項的元素。 「你想與類,而不是,您可以通過前面加上一個時期獲得元素:$(".product-configure-options-option ...

  2. $(this).find('select')查找這就是標籤的孩子一個SELECT元素。你想要它的兄弟姐妹,你可以用$(this).next('select')獲得。