Cha*_*han 113 javascript href attr
如何在按钮点击时通过Javascript 更改标签的href
属性值<a/>
?
<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>
Run Code Online (Sandbox Code Playgroud)
Nic*_*ver 155
没有href
,点击将重新加载当前页面,所以你需要这样的东西:
<a href="#" onclick="f1()">jhhghj</a>
Run Code Online (Sandbox Code Playgroud)
或者像这样阻止滚动:
<a href="#" onclick="f1(); return false;">jhhghj</a>
Run Code Online (Sandbox Code Playgroud)
或者return false
在你的f1
功能和:
<a href="#" onclick="return f1();">jhhghj</a>
Run Code Online (Sandbox Code Playgroud)
....或者,不引人注目的方式:
<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>
Run Code Online (Sandbox Code Playgroud)
jak*_*ans 28
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>
Run Code Online (Sandbox Code Playgroud)
这是一个额外的代码行,但发现它在结构上更好.
删除href
属性:
<a id="" onclick="f1()">jhhghj</a>
Run Code Online (Sandbox Code Playgroud)
如果链接样式很重要,那么:
<a href="javascript:void(f1())">jhhghj</a>
Run Code Online (Sandbox Code Playgroud)
这是我的看法。当用户按下“提交”按钮时,我需要通过从文本框中收集值来创建 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>
Run Code Online (Sandbox Code Playgroud)