我想获取父属性,但它返回未定义的jquery

时间:2017-01-08 06:38:23

标签: javascript jquery html custom-data-attribute

这是我的代码:



$(document).on('click', '.setting', function(e){
 alert($(this).parent().data('fieldtype'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="field">
  <div class="col-md-9 col-sm-6 col-xs-6 pad" style="">
    <textarea class="form-control field" name="key1" rows="3" data-fieldtype="test" data-group="">demo</textarea>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer movefield" data-key="1">
    <div><span class="glyphicon glyphicon-arrow-up"></span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer setting" data-key="1">
    <div><span class="glyphicon glyphicon-cog">click me</span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer field-remove" data-key="1">
    <div>x</div>
  </div>
</div>
&#13;
&#13;
&#13;

现在问题是没有获得data-fieldtype的值,因为它返回undefined这个方法。 并建议获取data-group的值,因为目前这个是空白

1 个答案:

答案 0 :(得分:0)

因为textarea不是.setting的父母。它的父级是#field,你应该在其中找到textarea。

$(this).parent().find('[data-fieldtype]').data('fieldtype')

&#13;
&#13;
$(document).on('click', '.setting', function(e){
  console.log(
    $(this).parent().find('[data-fieldtype]').data('fieldtype')
  );
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="field">
  <div class="col-md-9 col-sm-6 col-xs-6 pad" style="">
    <textarea class="form-control field" name="key1" rows="3" data-fieldtype="test" data-group="">demo</textarea>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer movefield" data-key="1">
    <div><span class="glyphicon glyphicon-arrow-up"></span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer setting" data-key="1">
    <div><span class="glyphicon glyphicon-cog">click me</span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer field-remove" data-key="1">
    <div></div>
  </div>
</div>
&#13;
&#13;
&#13;