简体   繁体   中英

I want to fetch the parent attribute but it returns undefined jquery

This is my code:

 $(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> 

Now the problem is not getting the value of data-fieldtype , as this method it returns undefined . And also suggest for getting the value of data-group as currently this one is blank

Because the textarea isn't parent of .setting . Parent of it is #field and you should find textarea in it.

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

 $(document).on('click', '.setting', function(e){ console.log( $(this).parent().find('[data-fieldtype]').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></div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM