我想将一个变量从 php 传递到 HTML 作为“属性”,以便 javascript (jQuery) 可以访问它。
$variable = addslashes( this is the text, coming from database, which can contain '' ' ' ' ' or "" " " " "" " or even <br><hr> tags );
HTML:
<img id="clickMe" titleAttr="<?php echo $variable; ?>" />
JS:
$('#clickMe').click(function() {
alert ($(this).attr('titleAttr'));
});
现在 Firefox 说这是一个错误的 HTML 代码,并且 alert()
显示文本直到第一个 ' 信号(其余被切断)
最佳答案
您需要 htmlspecialchars
而不是 addslashes
。
在任何情况下,几乎总是有比 addslashes
更好的转义机制,当没有时,addslashes
很少足够,因此您需要编写一个。
addslashes
在向 HTML 中插入数据时特别糟糕,因为 \
不是 HTML 中的转义字符。
关于javascript - 如何将变量作为属性从 php 传递到 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22810728/