gpt4 book ai didi

javascript - 从 html 字符串链获取参数值的正确语法

转载 作者:行者123 更新时间:2023-12-03 03:54:57 25 4
gpt4 key购买 nike

在这种情况下,获取具有两个参数的函数的参数值的正确语法是什么。

一开始我的removeRow(id)函数只需要一个参数来进行处理。

html代码:

"<a href=javascript:removeRow("+sport.id+"); class='btn btn-xs btn-warning'>remove</a>"

js代码://删除行

function removeRow(sportId) {
if ( 'undefined' != typeof sportId) {
console.log(sportId);
} else alert('Unknown id.');
}

现在,我希望这个函数接受两个参数(语法???)

html代码:

"<a href=javascript:removeRow("+sport.id+","+ event.id+"); class='btn btn-xs btn-warning'>remove</a>"

js代码:

// Remove row
function removeRow(sportId,eventId) {
if ( 'undefined' != typeof sportId) {
console.log(sportId+ " " + eventId);
} else alert('Unknown id.');
}

最佳答案

您需要引用 ID 并转义引号,如下所示:

"<a href='javascript:removeRow(\""+sport.id+"\",\""+event.id+"\")' class='btn btn-xs btn-warning'>remove</a>"

但我强烈建议您不要使用 javascript href 并使用数据属性

'<a href="#" onclick="return removeRow(this)" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="btn btn-xs btn-warning">remove</a>' 

并使用

function removeRow(link) { 
var sportId = link.getAttribute("data-sportid"),
eventId = link.getAttribute("data-eventid");
if ( 'undefined' != typeof sportId) {
console.log(sportId+ " " + eventId);
}
else alert('Unknown id.');
return false; // cancel the link
}

不引人注目地做同样的事情

window.onload=function() {
var sportLinks = document.querySelectoraAll(".sport");
for (var i=0;i<sportLinks.length;i++) {
sportLinks[i].onclick=function removeRow(e) {
e.preventdefault(); // cancel link event
var sportId = link.getAttribute("data-sportid"),
eventId = link.getAttribute("data-eventid");
if ( 'undefined' != typeof sportId) {
console.log(sportId+ " " + eventId);
}
else alert('Unknown id.');
}
}
}

添加一个类:

'<a href="#" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="sport btn btn-xs btn-warning">remove</a>' 

关于javascript - 从 html 字符串链获取参数值的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com