简体   繁体   中英

JavaScript onClick function constructed in PHP does not work in the ajax response back

I am sending an ajax request to load some information constructed in a div from PHP. There is an onClick function there. Ajax responds well, but the JavaScript function does not work in the HTML client.

This is the response from ajax written in PHP:

    $iscId = $row['instructorSemesterCourseId'];
    $year = $row['year'];
    $startDate = $row['startDate'];
    $endDate = $row['endDate'];
    $courseCredit = $row['courseCredit'];
    $pinned = $row['pinned'];
    $semesterName = $row['semesterName'];

    $date1 = date('F j, Y', strtotime($startDate)); 
    $date2 = date('F j, Y', strtotime($endDate));

    $div .= "<div id='SCid".$iscId."' class='schoolClass'>
                  <div class='schoolClassLeft'>
                    <div class='schoolCourseTitle'  onClick='classSessionEnter('SCid".$iscId."'); style='width:100%'>".$semesterName." ".$year." | ".$date1." &ndash; ".$date2."</div>
                  </div>
                </div>";
    echo('$div');

The function written in JavaScript and jQuery is:

function classSessionEnter(elm) {
    alert('elm');
    $('#' + elm).css({"background": "#E7F9CE"});
    $('#' + elm).css({"position": "absolute"});
    $('#' + elm).css({"top": "0px"});
    $('#' + elm).css({"color": "#006600"});
}

The alert does not work - it does not get into the function at all. Why?

Replace this

$div .= "<div id='SCid".$iscId."' class='schoolClass'>
              <div class='schoolClassLeft'>
                <div class='schoolCourseTitle'  onClick='classSessionEnter('SCid".$iscId."'); style='width:100%'>".$semesterName." ".$year." | ".$date1." &ndash; ".$date2."</div>
              </div>
            </div>";
echo('$div');

with this

$div .= "<div id='SCid".$iscId."' class='schoolClass'>
                  <div class='schoolClassLeft'>
                    <div class='schoolCourseTitle'  onClick='classSessionEnter(SCid".$iscId.");' style='width:100%'>".$semesterName." ".$year." | ".$date1." &ndash; ".$date2."</div>
                  </div>
                </div>";
    echo($div);
$div .= "<div id='SCid".$iscId."' class='schoolClass'>
    <div class='schoolClassLeft'>
        <div class='schoolCourseTitle' onClick=\"classSessionEnter('SCid".$iscId."')\"; style='width:100%'>".$semesterName." ".$year." | ".$date1." &ndash; ".$date2."</div>
     </div>
</div>";

You should esacpe the quotes first 「onClick=\\"」

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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