繁体   English   中英

.attr('href') 返回未定义

[英].attr('href') returning undefined

我正在使用一个简单的 JQuery 解决方案从链接中获取 href 并将其应用于单击事件。 这适用于 Webkit 和 Gecko 浏览器,但是 Internet Explorer (7 & 8) 一直将 href 位置显示为undefined 有人对此有修复吗? 可以帮我解决这个问题吗? 如果是这样,非常感谢。

 $('table tr').click(
    function () {
        var element = $(this).attr("class");
        var hrefLocation = $('#'+ element +' .deal-holder a').attr('href');
        alert(hrefLocation)
        window.location.href = hrefLocation;
        return false; 
    }
);

HTML 很简单:

 <tr class="QRG">
    <td class="blue"><a href="#QRG">QRG</a></td>
    <td>Company Sale</td>
    <td>Technology</td>
 </tr>


 <div class="deal" id="QRG">
      <p><span class="js">Overview</span><span class="no-js">Enham</span></p>
      <div class="deal-holder">
         <div class="image-holder">
             <img src="../assets/images/enham.gif" alt="" height="70" width="150" />
         </div>
         <p>Enham is a charity established in 1918, which delivers a wide range of essential services that provide choice and empowerment to disabled people to make their own decisions about their lives. Enham is a charity established in 1918, which delivers a wide range of essential services that provide choice and empowerment to disabled people to make their own decisions about their lives</p>
         <a class="moreInfo" href="individual.html">More Information</a>
      </div>
 </div>

没有什么让我觉得错了。

首先确保您使用的是最新版本的 jQuery,因为这有时会有所帮助。

我更改了您的代码,因此tr中的链接具有点击事件:

$('table tr a').click(function (e) {
    var element = $(this).closest('tr').attr("class"),
        hrefLocation = $('#'+ element +' .deal-holder a').attr('href');
    alert(hrefLocation)
    window.location.href = hrefLocation;
    e.preventDefault();
});

我在 这里 做了一个演示,它适用于 IE 7,8 和 9。希望这会有所帮助。

在不知道 html 代码的 rest 的情况下,很难确切知道您的问题是什么,行为很大程度上取决于您的html的结构...但是它只使用了$(this)的指针:获取子链接。

您可能需要 select 超链接组中的第一个元素。

$('table tr').click(
    function () {
        var element = $(this).attr("class");
        var hrefLocation = $('#'+ element +' .deal-holder a').eq(0).attr('href');
        alert(hrefLocation)
        window.location.href = hrefLocation;
        return false; 
    }
);

尝试将其包裹在准备好的 function 中。
IE 可能正在尝试将事件添加到 object 中,然后才进入 DOM:

$(document).ready(function(){

   $('table tr').click(
      function () {
         var element = $(this).attr("class");
         var hrefLocation = $('#'+ element +' .deal-holder a').attr('href');
         alert(hrefLocation);

         window.location.href = hrefLocation;
         return false; 
      });

});

暂无
暂无

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

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