简体   繁体   中英

My mess that I'm trying to do with PHP, MySQL, jQuery and css

Let's see if I can explain what I'm trying to do here..

I've got a MySQL Database with some info stored in it. I am using PHP to query the database, pull my selected entries out, put each one into a separate <div> (with Bootstrap framework). I have accomplished this part. Below is a snippet of what I'm doing...

 $query = "SELECT `quote`,`id` FROM `db`";
 $result = mysqli_query($con,$query);
   while($row = mysqli_fetch_array($result))
    {
      echo ' <div class="panel panel-info">
        <div class="panel-body text-muted" id="'.$row['id'].'">
    '.$row['quote'].'
  </div>
 </div>';
    }

Then I am wanting to use jQuery to add a css class on "click" to an individual <div> and be able to then use PHP to store the text of the "selected" <div> to a variable, for later use. This is the part I am struggling with, I can not figure out how to separate each individual <div> specifically and have jQuery add the class to it, because the "id" of div differs with every result from the db query.

To add a class to a div when it is clicked -

jQuery

$('div').click(function() {
    $(this).addClass('foo');
    var divText = $(this).text(); // store to JavaScript variable
});

Now that you have the JavaScript variable stored you can send it to a PHP function via AJAX.

What I would do is add a class to the <div> s, and use that to attach the event.

<div class="panel-body text-muted click-panel" id="'.$row['id'].'">

Then in your JavaScript, do something like:

$(function(){
    $('div.click-panel').click(function(){
        var div_id = this.id,
            div_text = $(this).text();

        if(/* some condition eg. div_id === 5 */){
            $(this).addClass('clicked');
        }
    });
});

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