简体   繁体   中英

Why is it that when I load this page, the href of an <a> tag is getting called?

I'm working on a project where I'm using an organization's header on my own website. The org's website is built on ASP.NET , which I know nothing about. The part that has been tripping me up is getting the search bar on the header to work. What I've tried is the following (with some things anonymized)

$(document).ready(function()
{
    /* Select the <a> element holding the search icon (usually a magnifying glass) 
       and set it as a variable: */
    var searchIcon = $('#id1');

    /* Set a variable equal to the prefix of the URL request: */
    var urlRequestPrefix = "http://www.orgname.com/search/Results.aspx?k=";

    /* Select the search <input> element and set it as a variable: */
    var searchInput = $('#id2');

    /* Make the <a> tag holding the search icon search for the input when clicked.
       Originally it has href="javascript:someFunction()"
    */
    searchIcon.attr('href', function()
    {
        window.location = urlRequestPrefix + searchInput.val();
    });
});

but unfortunately that is, for some reason, executing window.location = urlRequestPrefix + searchInput.val(); when the page loads. Can someone explain why and perhaps help me fix it?

该代码在文档加载时正在运行,将其设置为searchIcon的属性,请执行searchIcon.attr('href', '#').click(function () { window.location = urlRequestPrefix + searchInput.val(); });

Because of following code, it executes the function. Whereas you could have set href = some string value.

What it did - it just evaluated href parameter's value , in your case it is JS function , and it was expecting it to be string . So while evaluating, it redirected to other page as there is window.location = ... .

 searchIcon.attr('href', function()
    {
        window.location = urlRequestPrefix + searchInput.val();
    });

This should be like following.

searchIcon.attr('href', urlRequestPrefix + searchInput.val());

Assumption: <a> 's id is "id1".

Basically , this sets "href" value of anchor to required location. And on clicking that, ( by end user) it will do window.location = urlRequestPrefix + searchInput.val();

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