Mixing javascript, jQuery and PHP, newline

霸气de小男生 提交于 2019-12-11 12:58:14

问题


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:


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);


来源:https://stackoverflow.com/questions/16445663/mixing-javascript-jquery-and-php-newline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!