当我的html主体在php中时,Id选择器在jquery中不起作用


Id selector not working in jquery when my html body is in php

我在php标记中有html的主体,我希望onclick()能工作,但我希望jquery能处理它。我试图选择id,然后使用jquery的.on()方法,但它似乎不起的作用

这是我的php代码

<body>
<?php
$home=  
    "<div class='heading'  >
        <p><b>blah blah blah</b></p>
    </div>
    <div class='menu-wrap'>
        <nav class='menu'>
            <ul class='clearfix'>
                <li><a href='./member.php'>$username's Home</a></li>
                <li>
                    <a >States <span class='arrow'>&#9660;</span></a>
                    <ul class='sub-menu'>
                        <li><a onclick='changeAllStatesToFalse();'>ALL APPLIANCES OFF</a></li>
                        <li><a onclick='changeAllStatesToTrue();'>ALL APPLIANCES ON</a></li>
                        <li><a onclick='getStates();'>GET STATES</a></li>
                    </ul>
                </li>
                <li><a href='./security.php?userid=$username'>Security</a></li>
                <li><a >About me</a></li>
                <li><a href='./logout.php'>Logout</a></li>
            </ul>
        </nav>
    </div>
    <!3 Toggle Buttons start>
        <div class='buttonsArea'>
            <div class='display'>
                 <label class='label toggle'>
                      App-1
                     <input type='checkbox' class='toggle_input' id='button1' onclick='updateTable(1);'/>
                     <div class='toggle-control'></div>
                 </label>
            </div>
            <div class='display'>
                 <label class='label toggle'>
                      App-2
                     <input type='checkbox' class='toggle_input' id='button2' onclick='updateTable(2);'/>
                     <div class='toggle-control'></div>
                 </label>
            </div>
            <div class='display'>
                 <label class='label toggle'>
                      App-3
                     <input type='checkbox' class='toggle_input' id='button3' onclick='updateTable(3);' />
                     <div class='toggle-control'></div>
                 </label>
            </div>
        </div>
    <!3 Toggle Buttons end>";

    if($username && $userid){
        echo "$home";
        if($errormsg)
        echo "<script type='text/javascript'>alert('$errormsg');</script>";
    }
    else{
        header('Location:http://'.$raspiIp.'/EHDLOGIN_rpi/login.php');
        echo "<script type='text/javascript'>alert('Please Login');</script>";
    }

    ?>
</body>

这就是我想要的警报,当点击id为button1的按钮时

所以我在做:

$("#button1").on("click",function(){
alert(1);
});

但这并没有给我任何警告。Plz帮助

您正在动态创建元素,因此需要在DOM中注册事件,以便在元素可用时立即注册click事件处理程序。

$(document).on('click','#button1',function()
{
    alert();
});

http://jsfiddle.net/j6um1sq2/2/