简体   繁体   中英

jQuery object “.attr('href')” returns undefined

I have 2 links on my page. I'm trying to change the text of linkB when linkA is clicked. However, whenever I try to get the 'href' value of linkB, I'm getting an undefined error. I've been through a bunch of other threads here, but none have worked. Forgive me if I'm missing something obvious.

        <a ID="lnkPopUp" runat="server" style="text-decoration: underline; text-align: right" target="_blank">
            New Window
        </a>
        <br/>
        <a ID="lnkAlt" runat="server" style="text-decoration: underline; text-align: right" target="_blank" href="http://www.google.com">
            Not this one
        </a>

My script:

$('#lnkPopUp').click(
            function () {               
                var addressVal = $('#lnkAlt').attr('href');
                alert(addressVal);    
            }  

        );

Also, I've got my script inside the <head> tags. Could it be trying to get the href before the rest of the page has been processed and the href has been set?

Please let me know if any other info might help!

Try setting clientIDMode so that jquery is using the right ID.

<a ID="lnkAlt" clientIDMode="static" runat="server" style="text-decoration: underline; text-align: right" target="_blank" href="http://www.google.com">
    Not this one
</a>

If you are using .Net Framework 3.5 or lower clientIDMode is not going to work, because the property was added in .Net Framework 4

Try with this

   $('#lnkPopUp').click(
        function () {               
            var addressVal = $('#<%= lnkAlt.ClientID %>').attr('href');
            alert(addressVal);    
        }  
    );

and to change the href attribute use this code

$('#<%= lnkAlt.ClientID %>').attr("href", "http://stackoverflow.com/")

You have to use <%= lnkAlt.ClientID %> to get the generated ID; ASP.Net change the control's ID in the HTML generated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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