捕获链接文本并将其作为查询字符串附加到URL

capture link text and append to the URL as query string

本文关键字:字符串 查询 URL 链接 文本      更新时间:2023-09-26

我想捕获锚链接标签之间的文本并将其作为查询字符串传递给href值,因此它看起来像http://mysite.com/events/Pages/default.aspx?cat=cancer

我不能手动添加的原因是因为和之间的值是动态的。我如何捕获,并使用jquery或javascript附加到url ??

或者我可以在点击Cancer链接时,将其指向http://mysite.com/events/Pages/default.aspx?cat=cancer

<a href="http://mysite.com/events/Pages/default.aspx?cat="> Cancer</a>
$("a").on("click", function (e) {
    e.preventDefault();
    window.location = this.href + $.trim($(this).text());
});

或者您可以为每个链接替换href属性:

$("a").prop("href", function () {
    return this.href += $.trim($(this).text());
});

然后点击每个链接将自动引导用户正确。您的选择器($("a")应该更具体,取决于您的标记)

例子: http://jsfiddle.net/6U749/

编辑:如果你必须内联,这里有一个方法:

<a href="http://mysite.com/events/Pages/default.aspx?cat=" onclick="window.location.href = this.href + $.trim($(this).text());"> Cancer</a>

你可以这样做:

$('.someClassImStickingOnLinksThatNeedThisBehavior').each(function()
{
    this.href = $.trim(this.href) + $.trim(this.innerHTML);
});

然后,对于任何链接,它会自动将HREF更新为当前HREF加上节点的值。

你可以这样做:

var yourlink = $("#youlink");
var href = yourlink.attr("href");
var text = yourlink.html();
yourlink.attr("href", href + "?cat=" + text);