HTML+JavaScript:尽管使用了转义引号,但无法向onclick添加多个参数



我正在尝试在onclick函数中附加一个带有多个参数的HTMLdiv。即使我使用转义引号,HTML 也没有正确呈现。

这是我的 HTML:

$("#city-list").append("<div class='user-panel' id='" + user.id + 'onclick='openChat('' + user.id + '','' + user.username + '','' + user.sex + "'")><b>" + user.username + ", " + "(" + user.sex + ", " + user.age + ")</div>");

这是呈现的内容:

<div class="user-panel" id="A61o-ko0zVVJaxTbAAAHonclick=" openchat('a61o-ko0zvvjaxtbaaah','adamlee','male'")=""><b>adamlee, (male, 17)</b></div>

您错过了id属性和函数的结束引号onclick应该有双引号,因为其中使用了单引号。

const user ={id: 'a61o-ko0zvvjaxtbaaah', username: 'henryzhu', sex: 'male', age: 17 }
$("#city-list").append("<div class='user-panel' id='" + user.id + '' onclick="openChat('' + user.id + '','' + user.username + '','' + user.sex + "')"><b>" + user.username + ", " + "(" + user.sex + ", " + user.age + ")</div>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="city-list"></div>

您可以使用此代码在所有浏览器上工作,只需要正确使用引号,如以下代码所示:

$("#city-list").append("<div class='user-panel' id='" + user.id + "' onclick='openChat("" + user.id + "", "" + user.username + "", "" + user.sex + "")'><b>" + user.username + ", (" + user.sex + ", " + user.age + ")</b></div>");

如果你已经在使用 jQuery,为什么不使用 jQuery on click 函数呢?

并不是说使用onclick内联是错误的,但如果您好奇,这是实现目标的另一种方式。

// Add some data
var user = ({
"id":"a61o-ko0zvvjaxtbaaah",
"username":"henryzhu",
"sex":"male",
"age":"17"
});

var content = "";
// Set up your data in data-attributes
content += "<div class='user-panel'         
data-id='" + user.id + "'       
data-username='" + user.username + "' 
data-sex='" + user.sex + "'      
data-age='" + user.age + "'>";   
// viewable text
content += "<b>" + user.username + ", (" + user.sex + ", " + user.age + ")";
content += "</div>";
$("#city-list").append(content);
//---------------------------------------------------------------------
// jQuery on click function to call the openChat
// putting the data you need in data attributes let you grab what you need on the clicked name and
// submit it to the chat funciton.
$("body").on("click", ".user-panel", function(){
var userid = $(this).attr("data-id");
var username = $(this).attr("data-username");
var sex = $(this).attr("data-sex");
var age = $(this).attr("data-age");
openChat(userid , username , sex);
});
// Your chat function
function openChat(id, name, sex){
console.log(id + " | " + name + " | " + sex);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="city-list"></div>

如果您不需要支持 IE,则可能需要考虑在这种情况下使用反引号 ('(。它们提供功能性、更易读的体验,并且不易出错。更多信息在这里 模板文字的 MDN 文档。

带有反引号的示例是:

$("#city-list").append(`
<div class="user-panel"
id="${user.id}"
onclick="openChat('${user.id}', ${user.username}, ${user.sex})">
<b>${user.username}, (${user.sex}, ${user.age})
</div>
`)

最新更新