【问题标题】:How to update many links in a web page如何更新网页中的许多链接
【发布时间】:2015-03-10 13:25:07
【问题描述】:

我正在使用 MVC webgrid 和导航页面的工件是我有很多看起来像这样的 url:

<a href="/SyntheticData/MasterDetail?modelIn=Exact.Web.ViewModel.MasterDetailViewModel&amp;entrystate=Templates&amp;selectedrow=5">►</a>

我需要将 entrystate=Templates 更改为 entrystate=Paging

是否有 jscript 方法可以对简单脚本中的所有链接进行此更改?

链接是由 webgrid 组件生成的,我无权访问它。它们的形成似乎是因为网格采用调用动作的 url 并将其用作基本 url(entrystate 和 modelIn 是调用动作的路由值)。我无法控制这一点。我唯一的选择似乎是在创建 html 后对其进行修复。我被这个蹩脚的网格卡住了。

【问题讨论】:

  • "jscript way" 所以循环遍历每个'a'标签,查找和替换href属性,这是非常可行的
  • @KyleT in javascript?
  • 什么?他用javascript在客户端替换'a'标签href中的子字符串。不编辑纯文本文件

标签: javascript asp.net-mvc razor webgrid


【解决方案1】:

我希望有一些更简单的东西,但这看起来会起作用:

var links = $("a[href]");
for (var i = 0; i < links.length; i++) {
    var link = links[i];
    var urlin = link.attributes.getNamedItem("href");
    var urlout = urlin.value.replace("entrystate=Templates", "entrystate=Paging");
    var urlout2 = urlout.replace("entrystate=Designer", "entrystate=Paging");
    link.setAttribute("href", urlout2);
}

我最终使用了 (thx suncat100):

    $('a[href*="entrystate="]').each(function () {
        var url = $(this)[0].attributes.getNamedItem("href").value;
        url = url.replace("entrystate=Templates", "entrystate=Paging");
        url = url.replace("entrystate=Designer", "entrystate=Paging");
        $(this)[0].setAttribute("href", url);
    });
});

【讨论】:

    【解决方案2】:

    试试这个:

    $('a[href~="/SyntheticData/MasterDetail?"]').each(function() {
      $(this).attr('href', $(this).attr('href').replace('entrystate=Templates', 'entrystate=Paging'));
    });
    

    我使用通配符选择器来部分匹配 href,这样它就不会遍历不相关的链接。您可能需要对其进行调整。

    哎呀,你可能不会使用 jquery 吗?

    【讨论】:

    • 这正是我正在寻找的那种语法。谢谢!
    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2012-08-14
    相关资源
    最近更新 更多