如何使用jQuery访问父元素属性?

时间:2016-04-07 10:16:14

标签: javascript jquery

如何使用jQuery访问父元素属性?例如,下面的代码在我的网站中:

<div style="text-align: center;">
    <h3>Testing</h3>
     <p>
        <a style="display: inline-block;" href="http://www.google.com" target="_blank">
            <img class="alignleft size-full wp-image-3748" src="/wp-content/uploads/BBB336699.png" alt="BBB" height="45">
        </a>
        <a style="display: inline-block;" href="http://www.facebook.com" target="_blank">
            <img class="alignleft size-full wp-image-3749" src="/wp-content/uploads/COA336699.png" alt="COA" height="45">
        </a>
        <a style="display: inline-block;" href="http://portal.hud.gov/hudportal/HUD" target="_blank">
            <img class="alignleft size-full wp-image-3750" src="/wp-content/uploads/HUD336699.png" alt="HUD" height="45">
        </a>
        <a style="display: inline-block;" href="http://www.gmail.com/" target="_blank">
            <img class="alignleft wp-image-3921" src="/wp-content/uploads/HPF336699.png" alt="HPF" height="45">
        </a>
    </p>
</div>
$("a").click(function(event){ 
    var key = window.event.toElement;
    var re = /speridian/gi; 
    if (key.href.search(re) == -1) { 
        alert("it is not"); 
    } 
});

当我点击上面的链接时,我收到img元素事件属性,但我需要a元素事件属性,如toElement

你们有没有人可以帮我解决如何在这里获取锚元素事件的问题。提前谢谢!

2 个答案:

答案 0 :(得分:0)

  

使用.parent(SELECTOR)获取当前匹配元素集中每个元素的父元素(直接父元素),可选择通过选择器进行过滤。

$('img').on('click', function(e) {
  //e.stopPropagation();
  console.log($(this).parent('a').prop('href'));
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div style="text-align: center;">
  <h3>Testing</h3>
  <p>
    <a style="display: inline-block;" href="http://www.google.com" target="_blank">
      <img class="alignleft size-full wp-image-3748" src="/wp-content/uploads/BBB336699.png" alt="BBB" height="45">
    </a>
    <a style="display: inline-block;" href="http://www.facebook.com" target="_blank">
      <img class="alignleft size-full wp-image-3749" src="/wp-content/uploads/COA336699.png" alt="COA" height="45">
    </a>
    <a style="display: inline-block;" href="http://portal.hud.gov/hudportal/HUD" target="_blank">
      <img class="alignleft size-full wp-image-3750" src="/wp-content/uploads/HUD336699.png" alt="HUD" height="45">
    </a>
    <a style="display: inline-block;" href="http://www.gmail.com/" target="_blank">
      <img class="alignleft wp-image-3921" src="/wp-content/uploads/HPF336699.png" alt="HPF" height="45">
    </a>
  </p>
</div>

答案 1 :(得分:0)

The issue is because you're using the window.event. Use this to reference the clicked element instead:

$("a").click(function(e) { 
    e.preventDefault(); // stop the page being redirected
    var re = /speridian/gi; 
    if ($(this).prop('href').search(re) == -1) { 
        alert("it is not"); 
    } 
});