开发者

Jquery and dynamic id's

开发者 https://www.devze.com 2023-03-30 02:05 出处:网络
I have a Div in a while loop in PHP each with their own 开发者_StackOverflowid\'s, according to what id is in MySQL.With JavaScript i can simply add an onclick event handler to the Div and then call a

I have a Div in a while loop in PHP each with their own 开发者_StackOverflowid's, according to what id is in MySQL. With JavaScript i can simply add an onclick event handler to the Div and then call a function. Now for Jquery, how do i get the Div element for dynamic id's, do ?

<?php 
while($row =mysql_fetch_assoc($query))
{
$id= $row['id'];
echo "<div id='$id' >$id</div>"; 

} ?>


You should use a class instead of the id to identify the target. Add a class when you create the elements in PHP, and select on that instead.

<?php 
while($row =mysql_fetch_assoc($query))
{
$id= $row['id'];
echo "<div id='$id' class='someClass' >$id</div>"; 

} ?>

Client script:

$('.someClass')...


You can wrap all of your dynamically generated div tags inside another tag with a known id (let's call it container for example). Then, you can just loop through all of your generated div tags like this:

$('#container > div').click(function() {
    //your goodies here
});


I'm not a big php man, but you could prefix some static word before the row id to the div id (example: for row #3, dynamic_3)

<?php 
    while($row =mysql_fetch_assoc($query))
    {
        $id= $row['id'];
        echo "<div id='dynamic_$id' >$id</div>"; 
    } ?>

Then you can get the divs with jQuery as so:

$('div[id^="dynamic_"]')


you can use

$("Id*=yourdivid").click(function(){

//use this to access clicked div.
});

or if you have some specific class assigned to your div then you can use

$(".divclass").click(function(){
//this object will contain the div you clicked.
}) 


Another option you could chose to do is let use jquery to create the HTML markup (as opposed to PHP), where you would get a JSON / Array of controls to create, and then do something like:

var div=document.createElement('div');
$(div).html("My new Div")
    .click(function(){
//PUT your custom scripts here    
});

div.appendTo("#mainDiv");

now you can add that div to any container you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消