[英]Loading content into div from tabs
I am trying to use a php variable that holds an html snippet to display inside a div when an <li>
is clicked. 我试图使用一个包含html代码段的php变量,以在单击
<li>
时在div内显示。 The below code works if the variable only holds a string of text with no html. 如果变量仅包含没有html的文本字符串,则下面的代码有效。 But as soon as I add html it stops working.
但是,一旦我添加html,它就会停止工作。 What am I doing wrong?
我究竟做错了什么?
I have updated the code based on help I received below, but it is still not working. 我已经根据下面收到的帮助更新了代码,但是仍然无法正常工作。
This works: 这有效:
$(function() {
$('#tab-1').click(function() {
alert('click event called!'); var tabcontent = "Test Content";
document.getElementById('top-tabs-content').innerHTML = tabcontent;
});
});
This doesn't: 这不是:
$(function() {
$('#tab-1').click(function() {
alert('click event called!'); var tabcontent = "<?php echo json_encode($tabcontent[0]);?>";
document.getElementById('top-tabs-content').innerHTML = tabcontent;
});
});
Try to replace 尝试更换
var tabcontent = "<?php echo $tabcontent[1]; ?>"
with 同
var tabcontent = "'" + "<?php echo $tabcontent[1]; ?>" + "'";
Solution found! 找到解决方案! preg_replace and addslashes works to make the javascript correct.
preg_replace和addlashes可以使javascript正确。 The issue was that the html inside the variable was multiple lines, which doesn't work in a JS function.
问题是变量内的html是多行,在JS函数中不起作用。 Here is the way to set a JS var to a PHP var without it breaking:
这是在不破坏JS变量的情况下将JS变量设置为PHP变量的方法:
var tabcontent = "<?php echo preg_replace("/\r?\n/", "\\n", addslashes($tabcontent[1]));?>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.