简体   繁体   English

如何在onClick时将自定义href设置为按钮?

[英]How to set a custom href into a button when onClick?

I have a URL 我有一个网址

http://localhost:8080/BIM/teacher/reports/section-exercise/assignment?x=1&y=2&z=3

I have 2 btns 我有2个btns

在此处输入图片说明

I'm not sure how would I bind those 2 btn to the correct URL. 我不确定如何将这2个btn绑定到正确的URL。

If the Remediation is clicked, I want to set the href to 如果单击了“ Remediation ,则我要将href设置为

http://localhost:8080/BIM/teacher/reports/section-exercise/remediation?x=1&y=2&z=3

The only different is the 4th segment, the rest stay the same. 唯一的不同是第4段,其余保持不变。

Any helps / suggestions on them will be much appreciated ! 任何帮助/建议,将不胜感激!

I guess - I might have to : 我猜-我可能必须:

  • grab the whole URL 抓取整个URL
  • re-construct the newURL, store it in a variable 重建newURL,将其存储在变量中
  • bind that newURL to my btn. 将该newURL绑定到我的btn。

I hope I'm in the right track for this. 我希望我在正确的道路上。 Let me know if you guys, notice something. 让我知道你们是否注意到一些事情。

$(/*remediation button selector*/).click(function() {
    $(/*assignment performance button selector*/).attr('href', 'http://localhost:8080/BIM/teacher/reports/section-exercise/remediation?x=1&y=2&z=3');
});

I'm not sure if you meant you want the Remediation button to change the href for the first button, or if you want them to just have different hrefs; 我不确定您是否要让“修复”按钮更改第一个按钮的href,还是要它们仅具有不同的href? if it's the latter, they can just have the different hrefs directly in the HTML, no JS needed. 如果是后者,则它们可以直接在HTML中直接具有不同的href,而无需JS。

Here you can change the URL to what ever you like. 您可以在此处将URL更改为所需的URL。 I am using Replace fucntion to change the URL on the fly 我正在使用Replace fucntion即时更改URL

var url='http://localhost:8080/BIM/teacher/reports/section-exercise/assignment?x=1&y=2&z=3'

$('button1').click(function() {
    $(this).attr('href', url);
});
$('button2').click(function() {
    $(this).attr('href', url.replace('assignment','remediation');
});

Aminas answer is good, but in case the first URL isn't always the same I would recommend this function (using Regex) to change only the file name of an URL: Aminas的回答很好,但是如果第一个URL并不总是相同的话,我建议使用此函数(使用Regex)仅更改URL的文件名:

function changeFileName(strURL, strNewName) {
    return strURL.replace(/[^\/?]*(?=\?|$)/, strNewName);
}

This (a) works no matter what the original file name was, and (b) won't cause problem if the path contains the file name. 这(a)不管原始文件名是什么都有效,并且(b)如果路径包含文件名,则不会引起问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM