Javascript按钮onclick到一个web uri与location.href

javascript button onclick to a web uri with location.href

本文关键字:web 一个 uri href location onclick 按钮 Javascript      更新时间:2023-09-26

我试图添加一个onclick函数到<button>标签之外的按钮,在Javascript中。下面是我的时刻,但按钮没有链接到那个uri时,点击。我该怎么做呢?提前感谢您的帮助!我在代码中也做了注释。

对于按钮,我有:

"<td><button"+" id="+foodList[i].Id +" onClick="+"'"doSomething(this.id)'""+" >"+"Get"+"</button></td></tr>"

基本上我在for循环中给Get按钮分配了一个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 + "';"
  }

修改如下:

document.getElementById(id).onclick="location.href='"+uri+"';"

变成这样:

document.getElementById(id).onclick= function(){
    location.href = "Wanted url here"; // location.href = location.href + "/currentpath/additional/params/here"
}

这样,当你点击这个按钮时,你已经给它附加了一个函数,它改变了url(重定向页面)

你必须这样写:

document.getElementById(id).onclick = function() {
    location.href = uri; 
}
相关文章: