如何改变 href 属性值 <a/> 通过JavaScript在按钮上进行标记?

<script type="text/javascript">
  function f1()
  {
    document.getElementById("abc").href="xyz.php"; 
  }
</script>

<a href="" id="abc">jhg</a>
<a href="" id="" onclick="f1()">jhhghj</a>
有帮助吗?

解决方案

没有一个 href, ,点击将重新加载当前页面,因此您需要这样的内容:

<a href="#" onclick="f1()">jhhghj</a>

或阻止这样的滚动:

<a href="#" onclick="f1(); return false;">jhhghj</a>

或者 return false 在你的 f1 功能和:

<a href="#" onclick="return f1();">jhhghj</a>

....或者,不引人注目的方式:

<a href="#" id="abc">jhg</a>
<a href="#" id="myLink">jhhghj</a>

<script type="text/javascript">
  document.getElementById("myLink").onclick = function() {
    document.getElementById("abc").href="xyz.php"; 
    return false;
  };
</script>

其他提示

尼克·卡弗(Nick Carver)在那里做了什么,但我认为最好使用DOM SetAttribute方法。

<script type="text/javascript">
   document.getElementById("myLink").onclick = function() {
   var link = document.getElementById("abc");
   link.setAttribute("href", "xyz.php");
   return false;
   }
</script>

这是一条额外的代码行,但在结构方面发现它更好。

消除 href 属性:

<a id="" onclick="f1()">jhhghj</a>

如果链接样式很重要,则:

<a href="javascript:void(f1())">jhhghj</a>

要在单击它时动态更改链接:

<input type="text" id="emailOfBookCustomer" style="direction:RTL;"></input>
        <a 
         onclick="this.href='<%= request.getContextPath() %>/Jahanpay/forwardTo.jsp?handle=<%= handle %>&Email=' + document.getElementById('emailOfBookCustomer').value;" href=''>
    A dynamic link 
            </a>
<a href="#" id="a" onclick="ChangeHref()">1.Change 2.Go</a>

<script>
function ChangeHref(){
document.getElementById("a").setAttribute("onclick", "location.href='http://religiasatanista.ro'");
}
</script>

这是我的看法。当用户按下提交按钮时,我需要通过从文本框收集值来创建URL。

<html>
<body>

Hi everyone

<p id="result"></p>

<textarea cols="40" id="SearchText" rows="2"></textarea>

<button onclick="myFunction()" type="button">Submit!</button>

<script>
function myFunction() {
    var result = document.getElementById("SearchText").value;
	document.getElementById("result").innerHTML = result;
	document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result;
}		
</script>


<a href="#" id="abc">abc</a>

</body>
<html>

我知道它的旧帖子。尽管如此,它可能会帮助一些人。

如果可能的话,您也可以做到这一点。

 <script type="text/javascript">
        function IsItWorking() {
          // Do your stuff here ...
            alert("YES, It Works...!!!");
        }
    </script>   

    `<asp:HyperLinkID="Link1"NavigateUrl="javascript:IsItWorking();"`            `runat="server">IsItWorking?</asp:HyperLink>`

对此有任何评论吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top