简体   繁体   English

从父级或最近级Div获取数据值

[英]Get Data Value from Parent or Closest Div

I have this function that I am trying to get the data value of the outside div but I can't seem to get it to work, here is my code: 我有这个函数,我试图获取外部div的数据值,但似乎无法正常工作,这是我的代码:

I want the variable test to have the value of 1000. But I get undefined. 我希望变量test的值为1000。但是我不确定。

 function View() { var test = $(this).Parent().val; } function Hide() { var test = $(this).Parent().val; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div data-value="1000"> <a onclick="View();">View</a> <a onclick="Hide();">Hide</a> </div> 

 function View(anchor) { var test = $(anchor).parent().data('value'); console.log(test); } function Hide(anchor) { var test = $(anchor).parent().data('value'); console.log(test); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div data-value="1000"> <a onclick="View(this);">view</a> <a onclick="Hide(this);">hide</a> </div> 

Here is a JQuery solution for the problem. 这是针对该问题的JQuery解决方案。

 $('#hide').click(function() { alert($(this).parent().data('value')); }) $('#view').click(function() { alert($(this).parent().data('value')); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div data-value="1000"> <a id="view">View</a> <a id="hide">Hide</a> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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