如何在模式窗口上通过Javascript更改href属性

时间:2018-10-23 11:08:50

标签: javascript

我一直在寻找并尝试通过Java方式更改href属性的各种方法。几乎没有什么比其他方法更好。

此方法的问题是href上的变量不起作用。我猜有更好的方法在html标签中包含变量。

我真的很坚持,不胜感激。

这是模式窗口的代码:

<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">&times;</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href=enlace target="_blank">OK</a>
</div>
</div>

这是用户在显示模式窗口之前单击的按钮:

<script type="text/javascript"> 
var enlace;
</script> 
<button onclick="enlace='https://cloqq.com/actividad/tu-aventura-interactiva';return false" id="" class="go-btn pink-bg">Empieza a crear
</button>

2 个答案:

答案 0 :(得分:2)

  

https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

您可以使用setAttribute来重新分配href,在html中使用javascript的方式却不能那样工作。

const itemYouWantToUpdateHref = document.querySelector('.btn-ok')


function changeHref(link) {
  itemYouWantToUpdateHref.setAttribute('href', link);
}
<a class="btn-ok" href="www.google.com" target="_blank">My link will change</a>
<button onclick="changeHref('www.youtube.com')">click to change href from google to youtube</button>

答案 1 :(得分:0)

您可以仅对代码进行一些更改,而无需进行任何script tag使用代码本身。看下面的代码:

<button onclick="window.enlace='https://cloqq.com/actividad/tu-aventura-interactiva'" class="go-btn pink-bg">Empieza a crear</button>

<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">&times;</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href="javascript:window.open(window.enlace||'defaultAddress', '_blank');">OK</a>
<!--
   !! If you like to show an alert when the button is not clicked yet, try line below instead above line:
   <a class="btn-ok" href="javascript:window.enlace?window.open(window.enlace, '_blank'):alert('Please click the Button first!');">OK</a>
-->
</div>
</div>

,如果您在代码段上方运行并查看控制台,则可以看到一切正常(但由于安全问题,这些问题URL无效,则应将其复制到您的项目或空白html文件中以查看结果。)