JavaScript 不适用于 php echo

JavaScript doesn't work with php echo

本文关键字:echo php 适用于 不适用 JavaScript      更新时间:2023-09-26

我在使用 php javaScript echo 时遇到了问题。我想为使用 echo 动态创建的按钮触发一个 javaScript 函数。

当我在没有回声的情况下测试它时,函数使用正常。但是当我使用 echo 创建它时,它不起作用。

以下是页面中的回声.php:

$cont.='<div style="border-bottom: 1px solid #A2DBFF; padding-bottom: 25px; padding-top: 20px; margin-bottom: 10px; margin-left: 25px;">';
$cont.='<div class="SUBH">
        <input type="text" id="txtNEWHEADING" name="txtSubNam" placeholder="The new heading"  />
    </div>';
$cont.='<div class="PTAG">
        <p>
            <textarea rows="5" id="disNEWCONT" cols="70" placeholder="add a discription here.." name="txtCont"></textarea>
        </p>
    </div>';
$cont.='<div class="IMGTAG">
        <input type="file" id="imgNewIMAGE" />
        <button class="btnSav"  type="submit" onclick="SaveContent()" id="btnNEWCONTENT" style="margin-left: 300px;" />save</button>
    </div>';
$cont .= '</div>';

javaScript在这里:

$cont .= '
    <script type="text/javascript">
        $("#btnNEWCONTENT").click(function(){
            alert("hi there..");
            $.ajax({ url: ''ajax.php'',
                data: {action: ''test''},
                type: ''post'',
                success: function(data) {
                    alert(data);
                }
            });
        });     
    </script>
    ';
echo $cont;

请帮忙。

这段代码对我有用,在head之间添加了jquery,并将javascript包装到函数中:

<html>
<head>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<?php
 $cont='<div style="border-bottom: 1px solid #A2DBFF; padding-bottom: 25px; padding-top: 20px; margin-bottom: 10px; margin-left: 25px;">';
    $cont.='<div class="SUBH">
                <input type="text" id="txtNEWHEADING" name="txtSubNam" placeholder="The new heading"  />
            </div>';
    $cont.='<div class="PTAG">
               <p>
                  <textarea rows="5" id="disNEWCONT" cols="70" placeholder="add a discription here.." name="txtCont"></textarea>
              </p>
            </div>';
    $cont.='<div class="IMGTAG">
              <input type="file" id="imgNewIMAGE" />
              <button class="btnSav"  type="submit" onclick="SaveContent()" id="btnNEWCONTENT" style="margin-left: 300px;" />save</button>
            </div>';
$cont.='</div>';
$cont.='
    <script type="text/javascript">
    function SaveContent(){
        $("#btnNEWCONTENT").click(function(){
            alert("hi there..");
            $.ajax({ url: ''ajax.php'',
             data: {action: ''test''},
             type: ''post'',
             success: function(data) {
                 alert(data);
             }
        });
    });    } 
    </script>
    ';
    echo $cont;
?>
</body>
</html>