javascript - 为什么当我加载此页面时,<a> 标签的 href 被调用?

标签 javascript jquery asp.net

我正在开发一个项目,在我自己的网站上使用组织的标题。该组织的网站是基于 ASP.NET 构建的,对此我一无所知。让我困惑的部分是让标题上的搜索栏正常工作。我尝试过以下内容(有些内容是匿名的)

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

但不幸的是,由于某种原因,在页面加载时执行window.location = urlRequestPrefix + searchInput.val();。有人可以解释原因并帮助我修复它吗?

最佳答案

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

关于javascript - 为什么当我加载此页面时,<a> 标签的 href 被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430160/

相关文章:

jquery - 使用 Ajax 提交有关下拉列表更改的表单

javascript - 附加 html 按钮,然后调用其 onClick 事件 jquery

javascript - 如何保持滚动位置独立于回发?

c# - 动态添加TinyMCE编辑器到文本框

asp.net - 从服务器端创建菜单

php - jQuery 无法处理加载的内容

javascript - 正则表达式替换 javascript 中第一次出现的匹配项

javascript - 按每隔一行对表进行排序

javascript - Material Design LinearProgress 组件的工作示例

javascript - 关于 webapp 架构和 ReactJs 的建议