【发布时间】:2019-12-16 06:47:12
【问题描述】:
作为我使用的基础:http://stackoverflow.com/a/10997390/11236
点击时,我想获取被点击元素的数据属性值并将其用作 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 控制器
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
【问题讨论】:
标签: javascript jquery url-parameters