如何在嵌入式javascript函数中转义引号 [英] How to escape quotes inside an inline javascript function
本文介绍了如何在嵌入式javascript函数中转义引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的函数在没有在附加的div
中使用类的情况下运行得很好,但是当我尝试在元素上添加class
时,它无法正常工作.
My function is running perfectly without using class in appended div
but when I try to add a class
on the element it is not working.
<head>
<script type="text/javascript">
function showt(id){
$('body').append(id)
}
</script>
</head>
<body>
<a href="#" id="hidemain" onmouseover='showt("<div class='sdf'>appended</div>")'>show detail</a>
</body>
推荐答案
在其他引号内使用时,只需转义引号即可.也可以仅在属性内使用其他引号.因此,如果将属性包含在"
中,则只需在内部使用'
和\'
,并使用vica verse. (感谢@nnnnnn提到这一点!)
Just escape quotes, when used inside other quotes. Also just use the respective other quotes inside the attribute. So if you enclose the attribute in "
just use '
and \'
inside and vica verse. (Thanks to @nnnnnn for mentioning this!)
<a href="#" id="hidemain" onmouseover="showt('<div class=\'sdf\'>appended</div>')">show detail</a>
或
<a href="#" id="hidemain" onmouseover='showt("<div class=\"sdf\">appended</div>')">show detail</a>
编辑
为了获取事件对象,您应该以编程方式添加事件处理程序,如下所示:
In order to get the event object, you should add the event handler programatically like this:
<a href="#" id="hidemain">show detail</a>
<script>
document.getElementById( 'hidemain' ).addEventListener( 'click', function( event ) {
showt( '<div class="sdf">appended</div>' );
// here you have access to event and thus event.pageX
});
</script>
这篇关于如何在嵌入式javascript函数中转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文