简体   繁体   English

如何在jquery的append(),onclick(),alert()中一次转义单引号或双引号?

[英]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 这条路

  • you don't eval the code on click 你没有在点击时评估代码
  • syntax errors are direcly detected 语法错误被直接检测到
  • you won't have quote escaping problem 你不会有引用逃避问题
  • the code is more readable 代码更具可读性
  • you'll have a direct binding, without useless selector resolution 你将有一个直接绑定,没有无用的选择器分辨率
  • when you need a variable (for example 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 要在评论中回答您的问题,您也可以

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);
}

Demonstration 示范

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM