简体   繁体   English

尝试在PHP中回显JS函数

[英]Trying to echo JS function in PHP

I'm trying to echo a js function in HTML string inside PHP echo. 我试图在PHP echo内的HTML字符串中回显js函数。

And I can't figure it out : 我不知道:

$MY_JS_FUNCTION = '<script type="text/javascript">item + getLastField2()</script>';

if($row2->type == 'text') {
    echo "<li id='item-".$row2->rank."' class='list_item'>";
    echo "<textarea rows='2' id='".$row2->single_id."' cols='90' name='field[".$MY_JS_FUNCTION."]' data-kind='text' >".$row2->content."</textarea>";
    echo "</li>";
    echo '<br />';
}

Any ideas to get this work? 有什么想法可以进行这项工作吗? I think I have so much quotes in it or something like that... 我想我里面有很多引号或类似的东西...

Any help would be very very appreciated, thanks! 任何帮助将非常非常感谢,谢谢!

I'd reccommend storing the name in the database as well. 我建议也将名称存储在数据库中。 Then you can use $row2->name to insert the right name 然后,您可以使用$ row2-> name插入正确的名称

Your variable $MY_JS_FUNCTION contains an HTML <script> tag with some (strange) JavaScript code (missing a semi-colon). 您的变量$MY_JS_FUNCTION包含带有一些(奇怪的)JavaScript代码(缺少分号)的HTML <script>标记。 Based on your code the echo on line 5 results in this HTML: 根据您的代码,第5行的echo导致以下HTML:

<textarea ... name='field[<script type="text/javascript">item + getLastField2()</script>]' ... >...</textarea>

This is definitively not valid HTML. 这绝对不是有效的HTML。 And there is your problem... 还有你的问题...

It appears your intent is to echo that JS so that when the page loads, the JS actually sets the value of the name field for that textarea. 看来您的意图是回显该JS,以便在加载页面时,JS实际上为该textarea设置名称字段的值。 If that's the case, a simpler way might be something like this: 如果是这样,一种更简单的方法可能是这样的:

$MY_JS_FUNCTION = '<script type="text/javascript">document.getElementById("myTextArea").name = item + getLastField2()</script>';

if($row2->type == 'text') {
    echo "<li id='item-".$row2->rank."' class='list_item'>";
    echo "<textarea rows='2' id='".$row2->single_id."' cols='90' id='myTextArea' data-kind='text' >".$row2->content."</textarea>";
    echo $MY_JS_FUNCTION;
    echo "</li>";
    echo '<br />';
}

That will produce valid HTML. 这将产生有效的HTML。 The JS function will fire once that line is reached and update the "name" value to whatever the result of the function is. 到达该行后,JS函数将触发,并将“名称”值更新为该函数的结果。 Be sure to add the "id" field so that the JS knows which element to target. 确保添加“ id”字段,以便JS知道要定位的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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