.attr('href')返回undefined

时间:2011-08-15 15:24:10

标签: javascript jquery href window.location

我正在使用一个简单的JQuery解决方案从链接获取href并将其应用于click事件。这适用于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>

4 个答案:

答案 0 :(得分:4)

在错误的时候没有任何事情突然出现。

首先确保您使用最新版本的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();
});

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

答案 1 :(得分:1)

如果不知道你的其他html代码很难确切地知道你的问题是什么,那么行为在很大程度上取决于你的html的结构......但是在这里做一个快速测试它有效:Example,只是使用获取子链接的$(this)指针。

答案 2 :(得分:0)

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

$('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; 
    }
);

答案 3 :(得分:0)

尝试将其包装在就绪功能中。
IE可能正试图将事件添加到对象中,然后才进入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; 
      });

});
相关问题