将js变量插入html href标记

时间:2017-01-16 00:38:32

标签: javascript jquery html

基本上,尝试将不同的(字符串)值传递给变量

if (result == "A")
        finalLink.push("https://pool.wikitolearn.org/images/pool/d/d0/Not-giant-enough-letter-a.jpg");
if (result == "B")
        finalLink.push("https://img.clipartfest.com/a354883c247102b05c1657698b7bc8ed_-letters-b-23-b-boyjpg-the-letter-b-clipart_205-257.jpeg");
if (result == "C")
        finalLink.push("http://dailydropcap.com/images/C-9.jpg");

然后将变量发送到html href标记

<a id="button" href="finalLink">Click me to be redirected to your answer</a>

不太了解javascript,但在PHP中你可以通过添加{{variableHere}}来实现这一点

2 个答案:

答案 0 :(得分:2)

您可以这样做:

var result = "C";

switch(result) {
 case "A": 
   finalLink = "https://pool.wikitolearn.org/images/pool/d/d0/Not-giant-enough-letter-a.jpg"; 
   break;
 case "B":
   finalLink = "https://img.clipartfest.com/a354883c247102b05c1657698b7bc8ed_-letters-b-23-b-boyjpg-the-letter-b-clipart_205-257.jpeg"; 
   break;
 case "C":
   finalLink = "http://dailydropcap.com/images/C-9.jpg"
  break;
default:
}

$("#button").click(function (e){
 if( $(this).attr("href") == "#!" ){ // checks the current value of "href"
     $(this).attr("href", finalLink)  // sets the value of "href"
       .text("Click me to be redirected to your answer"); 
     e.preventDefault(); // prevents redirecting to the finalLink automatically
 }
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="button" href="#!" class="btn btn-success">Test me</a>

答案 1 :(得分:2)

Javascript的运作方式不同。当您执行类似于建议的操作时,您仍然在服务器上并生成发送到浏览器的HTML。

当您使用Javascript尝试相同时,HTML 已经发布,并且必须在运行时操作

要实现这一目标,您需要选择要修改的元素(在这种情况下,使用document.getElementById()很容易,因为您的链接实际上有id),然后使用DOM API方法DOMelement.setAttribute(attributename, value)

var finalLink, result;
var button = document.getElementById("button");

// example: result = "A"
result = "A";

function adjustLink() {
  switch(result) {
      case "A": 
        finalLink = "https://pool.wikitolearn.org/images/pool/d/d0/Not-giant-enough-letter-a.jpg"; 
        break;
      case "B":
        finalLink = "https://img.clipartfest.com/a354883c247102b05c1657698b7bc8ed_-letters-b-23-b-boyjpg-the-letter-b-clipart_205-257.jpeg"; 
        break;
      case "C":
        finalLink = "http://dailydropcap.com/images/C-9.jpg"
        break;
      default:
  }
  button.setAttribute("href", finalLink);
}
<a id="button" onclick="console.log(this.getAttribute('href')); return false;">Link</a>
<!-- return false; makes sure the link target is not followed (use only for this demo code) -->
<button onclick="result = 'A'; adjustLink();">Set result = "A"</button>
<button onclick="result = 'B'; adjustLink();">Set result = "B"</button>
<button onclick="result = 'C', adjustLink();">Set result = "C"</button>