将 link href/text 更改为单击按钮时文本框的值?

Change link href/text to value of a textbox on button click?

我想知道是否可以让 "a href" 元素的文本成为单击按钮时文本框的值。

$("#btn").click(function(){
$("#myLink").text($("#Coordinate1").val());
  $("#myLink").prop("href", "https://www.google.com/maps/place/" + $("#Coordinate1").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Coordinate1">
<button id="btn">Click</button>
<a id="myLink" href="#"><!-- THIS MUST BE VALUE OF "Coordinate1" --></a>

我希望解释足够清楚。

谢谢。

已解决: 添加了下面所选答案的代码。感谢大家的帮助,大家提供的解决方案都是我想要的。

是的,您可以,但是您必须在用户单击某些内容或完成输入 link 或其他一些事件时执行此操作。这里我使用了一个按钮:

$("#change").click(function() {  // when the button is clicked, change the href to whatever in the input + the root, and change it's text to the value as well
  var value = $("#Coordinate1").val();
  $("#myLink").prop("href", "https://www.google.com/maps/place/" + value) // change the href
              .text(value); // change the text content
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Coordinate1">
<a id="myLink" href="#">
  <!-- THIS MUST BE VALUE OF "Coordinate1" -->
</a>
<button id="change">Change</button>

我相信这就是您想要的。我采用了您已经拥有的代码,并将其放在单击我添加到页面的按钮元素中。还要确保在 a tag 中提供实际的文本值,否则用户将无法点击它。

$("#update").click(function() {
  $("#myLink").prop("href", "https://www.google.com/maps/place/" + $("#Coordinate1").val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Coordinate1">
<button id="update">update</button>
<a id="myLink" href="#">
Link
  <!-- THIS MUST BE VALUE OF "Coordinate1" -->
</a>

看来你想做这样的事情。

$("#btn").click(function(){
 $("#myLink").text($("#Coordinate1").val());
  $("#myLink").prop("href", "https://www.google.com/maps/place/" + $("#Coordinate1").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click</button>
<input type="text" id="Coordinate1">
<a id="myLink" href="#"><!-- THIS MUST BE VALUE OF "Coordinate1" --></a>

您可以使用以下代码:

function setLink() {
  var t = document.getElementById("Coordinate1").value;
  var h = "https://www.google.com/maps/place/" + t;
  var link = document.getElementById("myLink");
  link.href = h; //set link url
  link.innerText = h; //set link text (remove this line if you don't want it)
}
<input type="text" id="Coordinate1" oninput="setLink()">
<input type="button" value="get link" onclick="setLink()">
<div>
  <a id="myLink" href="#"></a><!-- THIS MUST BE VALUE OF "Coordinate1" -->
</div>