作为基础,我使用:http://stackoverflow.com/a/10997390/11236
单击时,我想获取被单击元素的 data 属性值并将其用作 url 参数。我不想破坏实际的行为,我只是想扩展它。我现在尝试了几个小时,但没有结果。
HTML
<div class="button one">Click me</div>
<div class="button two" data-url="this-should-be-the-parameter">Click me</div>
JS URL Controller
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
JS 点击处理程序
$( ".button" ).click(function() {
window.history.replaceState('', '', updateURLParameter(window.location.href, "specificurl", "customvalue"));
});
因此,我必须检查单击的 div 是否包含属性“data-url”,如果是,则应将其用作“customvalue”的参数
结果,Url 应如下所示:
Click on ".buton.one": xyz.com/?specificurl=customvalue
Click on ".buton.two": xyz.com/?specificurl=this-should-be-the-parameter
最佳答案
在现代浏览器中,有一个更简单的内置 URL API您现在可以使用。
在按钮单击处理程序中,使用 data()
检查数据属性是否已设置且具有值。如果是...使用 URL.searchParams.set(key, value)
$('.button').click(function(){
var url = new URL(location.href),
dataUrl = $(this).data('url');
if(dataUrl){
url.searchParams.set('someVar', dataUrl );
}
console.log(url.href)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button one">Click me</div>
<div class="button two" data-url="this-should-be-the-parameter">Click me</div>
关于javascript - 使用 data 属性中的值作为 url 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57414593/