将标记的内容插入到获取查询路径中



如何从以下位置获取内容:

<p id1="p-1-1"> Samsung Galaxy S8 Dual </ p>

并将其传递给参数:

<a href="/about?param=HERE" class="btn2"> Learn more </a>

由于 ajax 查询,p 标签的内容都会更改,我需要传输当前存在的内容。

您可以调用一个函数,该函数在单击时获取参数的值,而不是在页面加载时获取参数的值。

customRedirect = function(param){
location.href = "/about?param=" + param;
}
<p id="p-1-1"> Samsung Galaxy S8 Dual </p>
<a href="javascript:void(0)" onclick="customRedirect(document.getElementById('p-1-1').innerHTML)" class="btn2"> Learn more </a>

一个更好的方法(在我的情况下使用jquery(:

$("[customParam]").click(function(){
location.href = "/about?param=" + $('#' + $(this).attr('call') ).html()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p-1-1"> Samsung Galaxy S8 Dual </p>
<a href="javascript:void(0)" customParam call="p-1-1" class="btn2"> Learn more </a>

没有jquery:

var elems = document.querySelectorAll("[customParam]")
for(var i = 0; i < elems.length; i++){
elems[i].addEventListener("click", function(){
location.href = "/about?param=" + document.getElementById(this.getAttribute('call') ).innerHTML
})
}
<p id="p-1-1"> Samsung Galaxy S8 Dual </p>
<a href="javascript:void(0)" customParam call="p-1-1" class="btn2"> Learn more </a>

获取如下值:

var v = document.querySelector('p[id1="p-1-1"]').value;

并像这样设置参数:

var target = document.getElementsByClassName("btn2")[0];
target.href = target.href.substring(0, target.href.indexOf("=") + 1) + '"' + v + '"';

最新更新