[英]How to escape single quotes or double quotes within jquery's append(), onclick(), alert() at one time?
I have a question when i develop my html with javascript. 当我用javascript开发我的html时,我有一个问题。
What finally I want in html is: 我最终想要的是HTML:
<div id="test">
<div onclick="alert("it's a test.")">Show</div>
</div>
But in code I want it be realized like this: 但在代码中我希望它像这样实现:
<div id="test"></div>
<script>
var tmp="it's a test.";//be careful, there must be a single quote in this variable
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
</script>
In firebug it shows: 在萤火虫中它显示:
<div id="test">
<div ")'="" test.="" a="" s="" onclick="alert(" it">Show</div>
</div>
So i think it's an escaping problem. 所以我认为这是一个逃避问题。 But I think it has minimum 3 levels of depth. 但我认为它至少有3个级别的深度。 Anyone can help me? 有人可以帮帮我吗? Thanks! 谢谢!
Don't use jQuery to write inlined script. 不要使用jQuery来编写内联脚本。 Replace 更换
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
with 同
$('<div>').click(function(){ alert(" "+tmp+" ") }).text('Show').appendTo('#test');
This way 这条路
temp
), you don't need to put it in the global scope, it can be in the scope of the element addition 当你需要一个变量(例如temp
)时,你不需要把它放在全局范围内,它可以在元素添加的范围内 To answer your question in comment, you can either 要在评论中回答您的问题,您也可以
eventData
argument of jQuery's click function . 或者使用jQuery的click函数的eventData
参数。 Example of using jQuery's eventData
argument : 使用jQuery的eventData
参数的示例:
var names = ['A', 'B'];
for (var i=0; i<names.length; i++) {
$('<div>').text('link '+(i+1)).click(names[i], function(e) {
alert('Name : ' + e.data);
}).appendTo(document.body);
}
An easier way is to append new div
to your #test
then use event delegation to bind click event for your newly added div
like this: 更简单的方法是将新div
附加到#test
然后使用事件委托来绑定新添加的div
click事件,如下所示:
$('#test').append("<div class='newDiv'>Show</div>");
$('#test').on('click','.newDiv',function() {
alert("it's a test.");
});
Backslashes can be used to escape special characters 反斜杠可用于转义特殊字符
<div id="test"></div>
<script>
var tmp=\"it's a test.\";//be careful, there must be a single quote in this variable
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
</script>
That should work hopefully, if not it should help you get started 这应该是有希望的,如果不是它应该帮助你开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.