簡體   English   中英

javascript按鈕onclick到具有location.href的Web uri

[英]javascript button onclick to a web uri with location.href

我試圖在Java語言中將onclick函數添加到<button>標記之外的<button> 以下是我目前所擁有的,但是單擊該按鈕時未鏈接到該uri。 我應該怎么做? 非常感謝您的提前幫助! 我也在代碼中評論了。

對於按鈕,我有:

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

因此,基本上,我在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 + "';"
  }

更改此:

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; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM