【问题标题】:javascript button onclick to a web uri with location.hrefjavascript 按钮 onclick 到带有 location.href 的 web uri
【发布时间】:2015-10-12 08:31:49
【问题描述】:

我正在尝试在 Javascript 中将 onclick 函数添加到 <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 + "';"
  }

【问题讨论】:

    标签: javascript html button onclick uri


    【解决方案1】:

    改变这个:

    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(重定向页面)

    【讨论】:

    • 感谢您的回复!但是如果它不是一个窗口位置,而是一些 web uri 呢?
    • @user3735871 是一样的。只需执行以下操作:window.location = 'http://google.com'
    • 但是在这种情况下我应该如何处理按钮标签?似乎如果我将onclick = doSomething(id) 添加到&lt;button&gt; 标记中,我需要双击它以触发 function() 去那个 uri ..
    • 什么?不,发布一些代码。你做错了什么
    • 我在问题中对其进行了编辑。所以我在按钮标签中有一个onclick=doSomething(id),将按钮链接到doSomething 函数。我一定做错了。我该如何解决这个问题?
    【解决方案2】:

    你必须这样写:

    document.getElementById(id).onclick = function() {
        location.href = uri; 
    }
    

    【讨论】:

    • 谢谢伙计。我不知道为什么答案被否决了。这个对我有用。我赞成它
    • 问题是当我将onclick = doSomething(id) 添加到&lt;button&gt; 标签时,我需要双击它才能触发function() 去那个uri..
    猜你喜欢
    • 1970-01-01
    • 2014-11-04
    • 2014-03-11
    • 2016-09-08
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多