隐藏的字符导致JQuery函数失败 [英] Hidden characters causing JQuery function to fail

查看:45
本文介绍了隐藏的字符导致JQuery函数失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解导致简单jquery函数失败的原因。它只是查找ID,用其他数据替换一些内容。我有$ data1,$ data2,$ data3作为... more的替换测试数据。替换适用于$ data1和$ data2,但$ data3失败。不幸的是,我需要使用的所有数据都是$ data3格式。

I am trying to understand what causes a simple jquery function to fail. It simply looks for the ID, replaces some content with other data. I have $data1, $data2, $data3 as the replacement test data for "...more". The replace works for $data1 and $data2, but fails for $data3. Unfortunately, all of the data I need to work with comes in $data3 format.

测试代码如下:

<?php
  $data1 = '<p>line one text here</p>'; 
  $data2 = '<p>line one text here</p><p>line two text here</p><p>line three text here</p>';
  $data3 = <<<EOF
    <p>line one text here</p>
    <p>line two text here</p>
    <p>line tgree text here</p>
EOF;
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            //To get remainder of article when clicked on "...more"
            $(document).ready(function () {
                $("#more").click(function () {
                    $("#more").html('<?= $data2; ?>');
                    $("#more").css('color', 'black');
                    $("#more").css('cursor', '');
                });
            });
        </script>
    </head>
    <body>
        <p class="card-text"><span id="more" style = "color: blue; cursor:pointer;">...more</span></p>  
    </body>
</html>

查看控制台,我看到jquery代码中的数据显示$ data1的单个连续行和$ data2,但是,对于$ data3,有明显的换行符,这是我怀疑导致失败的原因(脚本什么都不做,没有发生更改)。见下图:

Looking at the console, I see that the data in the jquery code shows single continuous lines for $data1 and $data2, however, for $data3, there are clearly line breaks which is what I am suspecting is causing the failure (script does nothing, no change-out occurs). See graphic below:

我如何找到这些隐藏的字符是什么造成的问题,以便我可以在提交到jquery函数之前删除/替换所有这些,或者有没有办法事先在函数中处理它?感谢任何其他见解。

How would I find out what these hidden characters are that are creating the problem so that I can remove/replace all of them before submitting to the jquery function, or is there a way to process it in the function beforehand? Any other insight is appreciated.

提前致谢!

推荐答案

要解决这个问题,您需要在JS代码中使用模板文字,即。用`而不是'分隔字符串。这是因为它们允许字符串文字中的换行符,如PHP所示:

To fix this you will either need to use template literals in your JS code, ie. delimit the string with ` instead of ' or ". This is because they allow line breaks within the string literal, as PHP does:

$("#more").html(`<?= $data2; ?>`);

请注意,这在IE11中不受支持

Note that this is unsupported in IE11 and lower.

或者你需要在输出到JS之前替换PHP中字符串中的换行符。

Alternatively you will need to replace the line breaks in the string in PHP before it's output to the JS.

这篇关于隐藏的字符导致JQuery函数失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆