Mixing javascript, jQuery and PHP, newline

2019-08-09 09:48发布

Ok, so I have a few things here:

Javascript:

desc = "line 1 \n line 2"

jQuery:

$("#msg").text(desc);

PHP:

const NUM = 555;

What I want, is to change the text of the <p> with the id of msg, so that it would contain a piece of text with a number of lines, and in one of them the number from the PHP constant.

Like so:

Line 1
Line 2 555, Line 2 continued
Line 3

My problem is how do I mix them all? I tried the following:

var desc = "line 1 \n line2" + <?php echo NUM ?> +"\n line 3"; and that doesn't work.

1条回答
别忘想泡老子
2楼-- · 2019-08-09 10:29

There are several issues with your code:

  • PHP constants should be defined using define("CONSTANT_NAME", "VALUE"); syntax;
  • \n has no effect inside HTML tag (if you dont apply white-space: pre; or pre-wrap);
  • <?php echo NUM; ?> should be wrapped with " or should be inside JavaScript string;
  • $("#msg").text(desc) will remove all tags from desc, thus you need to use .html(desc) instead.

What you need is something like this:

PHP

define("NUM", 555);

JavaScript

var desc = "line 1<br/>line2 <?php echo NUM; ?><br/>line 3";
$("#msg").html(desc);
查看更多
登录 后发表回答