如何在 jquery 中使用蛋糕元素?

我正在使用 CakePHP 3,让我告诉你我想要做什么,是使用屏幕宽度条件在 div 中显示蛋糕元素,它会引发以下错误Uncaught SyntaxError: Unexpected identifier。我已经告诉你,语法没有任何反应,没有逗号、句号等。我错过了。


我需要知道的是把元素助手放在jquery里面的正确方法这个:<?= $ this->element('Search/Legislacion/form-search-legis') ?>


<script>

    $(document).ready(function(){

        var width = $(document).width(),

            search_form_legis = "<?= $this->element('Search/Legislacion/form-search-legis') ?>"; 


        // console.log(width);


        if(width >= 576){

            $('#searchDesktop').html(search_form_legis);

        }

    });

</script>


当年话下
浏览 70回答 1
1回答

猛跑小猪

您不能只将 HTML 转储到 JavaScript 字符串中,一旦出现第一个单引号/双引号,它就会破坏事物,因为这将关闭字符串,只需查看正在交付的页面的源代码,就会有像这样的东西:search_form_legis = "<form method="POST" action="/url">...";显然这是语法错误。如果您想将来自 PHP 的数据放在 JavaScript 中,那么建议使用json_encode(),它会将数据转换为正确的格式。var search_form_legis = <?= json_encode(&nbsp; &nbsp; $this->element('Search/Legislacion/form-search-legis')) ?>;一个字符串,如你的情况,将自动被引用和转义,即你甚至不需要在它周围加上引号,它看起来像这样:var search_form_legis = "<form method=\"POST\" action=\"/url\">...";话虽如此,如果根本没有不输出内容的充分理由,那么您可能需要考虑使用 CSS 规则来隐藏/显示它,类似于以下内容:#searchDesktop {&nbsp; &nbsp; display: none;}@media (min-width: 576px) {&nbsp; &nbsp; #searchDesktop {&nbsp; &nbsp; &nbsp; &nbsp; display: block;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript