简体   繁体   中英

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. The below code works if the variable only holds a string of text with no html. But as soon as I add html it stops working. 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. The issue was that the html inside the variable was multiple lines, which doesn't work in a JS function. Here is the way to set a JS var to a PHP var without it breaking:

var tabcontent = "<?php echo preg_replace("/\r?\n/", "\\n", addslashes($tabcontent[1]));?>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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