简体   繁体   English

为什么在我加载此页面时, <a>会调用标签</a>的href <a>?</a>

[英]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. 该组织的网站建立在ASP.NET ,我对此一无所知。 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(); 但不幸的是,由于某种原因,执行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. 而您可以设置href =一些字符串值。

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 . 它做了什么 -它只是评估href参数的值,在您的情况下,它是JS function ,并且期望它是string So while evaluating, it redirected to other page as there is window.location = ... . 因此,在进行评估时,由于存在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". 假设: <a>的ID为“ id1”。

Basically , this sets "href" value of anchor to required location. 基本上,这会将锚的“ href”值设置为所需位置。 And on clicking that, ( by end user) it will do window.location = urlRequestPrefix + searchInput.val(); 然后单击(由最终用户),它将执行window.location = urlRequestPrefix + searchInput.val();

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

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