以通用方式访问great-grantparent元素

时间:2017-11-21 11:04:14

标签: javascript jquery html

我有一个带有几个div的HTML结构,如下所示:

<div class="radio-button-category">
     <input type="hidden" class="appointment" name="salutation" id="salutation">
     <div class="radio-button-wrapper">
          <div class="mod_6">
              <div class="radio-button-wrapper">
                   <span class="radio-button" data-value="M" data-input="#salutation"></span>
                   <span>Sr.</span>
             </div>
          </div>
          <div class="mod_6">
              <div class="radio-button-wrapper">
                  <span class="radio-button" data-value="F" data-input="#salutation"></span>
                  <span>Sra.</span>
              </div>
          </div>
   </div>
</div>

所以现在,我希望从点击时更改其值来访问标签,我需要一个比这更优雅的解决方案:

 $('span.radio-button').parent().parent().parent().siblings('input').val($(this).data('value'));

我尝试过find(),nearest()......但没有任何效果。谢谢:))

1 个答案:

答案 0 :(得分:0)

$(document).on('click','.radio-button',function(){ 
   var inp_data = $(this).parents().siblings('input').data("value");  
   //var inp_data = $(this).data("value");  // if you want M to F values
     console.log(inp_data);
     
     
     
});
 .radio-button {
    padding: 5px; 
    border: none;
  border-radius:100%;
    background: red;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-button-category">
     <input type="hidden" class="appointment" data-value="your value" name="salutation" id="salutation">
     <div class="radio-button-wrapper">
          <div class="mod_6">
              <div class="radio-button-wrapper">
                   <span class="radio-button" data-value="M" data-input="#salutation"></span>
                   <span>Sr.</span>
             </div>
          </div>
          <br>
          <div class="mod_6">
              <div class="radio-button-wrapper"> 
                  <span class="radio-button" data-value="F" data-input="#salutation"></span>
                  <span>Sra.</span>
              </div>
          </div>
   </div>
</div>