1

我正在构建一个代码片段系统并使用 jQuery 来显示编辑器。我注意到 jQuery 喜欢注释掉任何内联 PHP 代码。有没有办法防止这种情况发生:

<textarea id='beep'></textarea>

jQuery代码:

var code = "<div>Why <?php echo 'hello'; ?> there!</div>";
var parsed = $(code).html();
$('#beep').val(parsed);

这是我想在 textarea 中看到的:

Why <?php echo 'hello'; ?> there!

但是 jQuery 将其修改为如下所示:

Why <!--?php echo 'hello'; ?--> there!

我知道这可能是一种安全措施,但有没有办法阻止这种情况发生?

我知道我可以使用 HTML 实体来解决这个问题,但由于这个工具的性质,它会干扰发布的有意包含 html 实体的代码片段。

JSFiddle:http: //jsfiddle.net/YB4fD/1/

附加节点:一些答案建议我在没有 jQuery 的情况下使用 JavaScript 来处理这个问题,但我需要 jQuery。我的字符串包含我正在使用 jQuery 解析的 DOM 树。

4

2 回答 2

1

尝试这个:

var code = "<div>Why &lt;?php echo 'hello'; ?&gt; there!</div>";
于 2013-02-09T02:01:20.393 回答
0

这可以解决问题。

var code = "Why <?php echo 'hello'; ?> there!";
document.getElementById('beep').appendChild(document.createTextNode(code));

在 textarea-element 中使用其他元素是无效的。

于 2013-02-09T01:24:34.967 回答