[英]Whats a cleaner way to append something to a link URL?
I've got this code so far, which isn't working: 到目前为止我已经有了这个代码,但是没有用:
$('.passName').click(function(){
var schoolName = "18734";
var link = $(this).attr('href');
var newLink = link + schoolName;
$(this).attr('href') = newLink;
});
请执行下列操作:
$(this).attr('href', newLink);
There is a problem with your approach : you're appending the schoolName to the URL each time you click, even if the user targets another tab. 您的方法存在问题:每次单击时都会将schoolName附加到URL,即使用户定位到另一个选项卡也是如此。
So I'd suggest to not mess with the href
attribute but do the action on click : 所以我建议不要弄乱
href
属性但是点击动作:
$('.passName').click(function(){
location.href = this.href + "18734";
});
or at least check you didn't add it before : 或者至少检查一下你之前没有添加它:
$('.passName').click(function(){
var schoolName = "18734";
var link = this.href;
if (link.indexOf(schoolName, link.length - schoolName.length)!==-1) {
this.href = link+schoolName
}
});
or, as suggested by Felix Kling, simply ensure the function is called only once : 或者,正如Felix Kling建议的那样,只需确保只调用一次函数:
$('.passName').one('click', function(){
this.href += "18734"
});
In Simple, do this way:- 在Simple中,这样做: -
$('.passName').click(function() {
$(this).attr('href', this.href+'18734');
});
You actually don't need to create a new jQuery object, you can simply have: 您实际上不需要创建新的jQuery对象,您可以简单地:
$('.passName').click(function() {
var schoolName = "18734";
this.href += schoolName;
});
Library as jQuery as useful but we shouldn't forgot the plain JavaScript and DOM. 库作为jQuery很有用,但我们不应该忘记简单的JavaScript和DOM。
Plus, in JS you can't really "assign" something to a function call as you made; 另外,在JS中,你无法真正为函数调用“分配”某些内容; in jQuery the way to set an attribute's value is
$(this).attr('attr', newLink)
在jQuery中设置属性值的方法是
$(this).attr('attr', newLink)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.