我有一个包含一系列 <a>
链接的页面,如下所示:
<a href="http://www.domain.com/page/other.jsf?fruit=apple&tree=pine&rock=sedimentary">click me</a>
这些参数以较小的方式操纵链接到(“other.jsf”)的最终页面的内容。
作为 A/B/n 测试的一部分,我想根据包含链接的页面上的用户行为更改 href 中的参数。因此,例如,我想在单击之前将水果参数更改为“橙色”。
我的问题是参数改变了字符串中的位置,或者对于某些链接可能根本不存在,并且 .param() 函数似乎只适用于 url。
到目前为止(基于另一个问题的答案)我有这个,但它没有说明可能没有“end_pos”或者 href 中缺少“fruit=”的可能性(尽管这第二点似乎更容易使用 if undefined 类型的函数修复):
$('a').each(function () {
if ($(this).attr('href').indexOf('other') > -1) {
var hrefStr = $(this).attr('href');
var start_pos = hrefStr.indexOf('fruit=') + 1;
var end_pos = hrefStr.indexOf('&',start_pos); //works as long as fruit=apple is in the middle or front of the string
var fruit = hrefStr.substring(start_pos,end_pos);
...
//put modified href back in <a>
}
});
我的第二个问题是识别原始 href 的相同部分以将新字符串放回原处。不过,在首先了解提取它的方法之后,我可能会得到这个。
我还应该说,除了通过 JavaScript,我无法控制 .jsf 页面
原文由 tymothytym 发布,翻译遵循 CC BY-SA 4.0 许可协议
You could use Attribute Contains Selector [name*=“value”]
"a[href*=fruit]"
to selecta
elements that contain"fruit"
athref
attribute,.attr(attributeName, function)
,String.prototype.replace()
替换"apple"
"orange"