[英]javascript button onclick to a web uri with location.href
I am trying to add a onclick function to a button outside of the <button>
tag, in Javascript. 我试图在Java语言中将onclick函数添加到
<button>
标记之外的<button>
。 Below is what I have at the moment, but the button doesn't links to that uri when clicked. 以下是我目前所拥有的,但是单击该按钮时未链接到该uri。 How should I do this?
我应该怎么做? Many thanks for your help in advance!
非常感谢您的提前帮助! I commented in the code as well.
我也在代码中评论了。
For the button I have: 对于按钮,我有:
"<td><button"+" id="+foodList[i].Id +" onClick="+"\"doSomething(this.id)\""+" >"+"Get"+"</button></td></tr>"
So basically I assigned the "Get" button an id in a for loop. 因此,基本上,我在for循环中为“获取”按钮分配了一个ID。
function doSomething(id) { //the button's id
var item = document.getElementById("type").value; //get some value from elsewhere in the page
if (item == "food") {
var uri = "baseuri" + id;
document.getElementById(id).onclick = "location.href='" + uri + "';"//add an onclick to the button so that it will takes the user to that uri
} else {
var uri = "another baseuri" + id;
document.getElementById(id).onclick = "location.href='" + uri + "';"
}
Change this: 更改此:
document.getElementById(id).onclick="location.href='"+uri+"';"
to something like this: 像这样:
document.getElementById(id).onclick= function(){
location.href = "Wanted url here"; // location.href = location.href + "/currentpath/additional/params/here"
}
That way, when you click the button, you have attached a function to it, and it changes the url (redirects the page) 这样,当您单击该按钮时,您已经在该按钮上附加了一个函数,并且该函数会更改url(重定向页面)
You must write it like this : 您必须这样写:
document.getElementById(id).onclick = function() {
location.href = uri;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.