douzhaishan5462 2013-12-26 12:32
浏览 157
已采纳

如何使用Jquery查找最近的父元素属性值

I am facing a problem on getting the nearest parent element attribute value using Jquery. Can anyone help me on this. My element structure is as below,

<ul class="Someclass">
<li><span id=3 class="heading"></span>
  <ul>
    <li>
     <ul> <li><span ><button onclick= "redirect()"></button></span</li>
     <ul>
    </li>
  </ul>
</li>
<ul>

<script type="text/javascript">
function redirect() {
    alert(....)
}
</script>

In the above code when i click that element having onclick event i want to get the value as 3 in alert() which is in the element having the class heading. The above code is in for loop so it will have more code like this in a same page.

  • 写回答

6条回答 默认 最新

  • duanqianhuan3994 2013-12-26 12:38
    关注

    With your current code, pass the clicked element reference to the function like

    <button onclick= "redirect(this)">asdf</button>
    

    then

    function redirect(el) {
        alert($(el).closest('.Someclass > li').children('span').attr('id'))
    }
    

    Demo: Fiddle

    Bu a more recommended way will be is to use jQuery event handlers like

    <button class="redirect">asdf</button>
    

    then

    jQuery(function($){
        $('.Someclass .redirect').click(function(){
            alert($(this).closest('.Someclass > li').children('span').attr('id'))
        })
    })
    

    Demo: Fiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!