简体   繁体   中英

JQuery click event is not being registered on <ul> returned from PHP Script

I have a HTML page which contains 2 div s. In its first div a ul is populated immediately after page loading using AJAX from a PHP script. And 2nd div there is a static ul . Now I want that in both div s on every ul a click event should work. Ie, an alert should come saying that it's clicked.

Here is the PHP code:

require_once "../../resources/script/dbconfig.php";

$query = "SELECT * FROM job_case";
$rslt = mysqli_query($link,$query);     

echo "<ul>";

for($i=0;$i<mysqli_num_rows($rslt);$i++)
{
$job = mysqli_fetch_row($rslt);
echo "<li class=\"jobTitle\" id=jon".$job[0].">".$job[1]."</li>";           
}

echo "</ul>";

HTML Page:

<div class="jobCase" id="govtJobCase">
    <ul>
        <li class="jobTitle" id="jobId">Item A</li>
        <li class="jobTitle" id="jobId">Item B</li>         
    </ul>
</div>        
<div class="jobCase">
    <ul>
         <li class="jobTitle" id="jobId">Item A</li>
         <li class="jobTitle" id="jobId">Item B</li>
     </ul>        
 </div>

My problem is it that in first div published from PHP, there is no event working but in other static ul tag event is working properly.

you should provide us with your jQuery script. But I can help you maybe:

for the event, you should not use on() and rather better to stick to delegate() since it allows event attachment to the DOM objects which are yet to be created after the initial page load. For instance if your ajax requests returns a <uL class='sample'></ul> you can then do:

$(document).delegate(".sample", "click", function(){
alert("You have clicked on a newly created <ul>");
});

If you put the event handler on an element around both divs you can update the contents of the element all you want but the event handler stays in tact.

<div class="container">
    <!-- the contents of this div is populated using AJAX -->
</div>

javascript:

$('.container').on('click', function () {
    // clicks will arrive here even when they originate from ajax loaded content
});

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