Dynamic jQuery selectors with php while loop

I have a while loop that creates a list of binding tags, each of which has a unique class name, counting from 1 to any number of elements. I would like to change the css attriubute to a specific tag and anchor class when it is clicked, so lets say that the background color is changed. Here is my code

while($row = mysql_fetch_array($results)){
 $title = $row['title'];
 $i++;
 echo "<a class='$i'>$title</a>

}

I would like my jquery to look something like this, it will obviously be more complicated than that. I just got confused how to start.

$(document).ready(function() {
$('a .1 .2 .3 .4 and so on').click(function() {
$('a ./*whichever class was clicked*/').css('background':'red');
        });
   });
+3
source share
4 answers

Can you give the class a more consistent name? For example myClass_1, myClass_2etc.

Then you could do:

$(document).ready(function() {
    $('a[class^=myClass_]').click(function() { // Assign handler to elements with a
                                               //  class that starts with 'myClass_'
        $(this).css('background','red');  // Change background of clicked one.

    });
});

" " , myClass.

.

$(this) , .

: http://jsfiddle.net/Jurv3/

" ": http://api.jquery.com/attribute-starts-with-selector/

EDIT: ]. .

+2

, :

var myclasses = [".1",".2",".3"]; // generated by php

$.each(myclasses, function(index, value) { 
    $('a '+value).click(function() {
        $(this).css('background':'red');
    });
});

. , . .

+2

, , myClass. :

$('a.myClass').click(function () {
    $(this).css('background':'red');
});

, - . $(this).parent().css(...), $(this).next().css(...) ..

+1

- ?

while($row = mysql_fetch_array($results)){
 $title = $row['title'];
 $i++;
 echo '<a class="anchor_link" id="'.$i.'">'.$title.'</a>';

}

jQuery:

$(document).ready(function() {
    $('a.anchor_link').click(function() {
        var thisAnchor = $(this).attr('id');
        $(this).css('background':'red');
    });
});

The reason I added js var 'thisAnchor' is because I assume you need this $ i php variable as a binding marker? if so, you can just take js var and use it as you need. if you cannot use the identifier because the linked content is marked with id, use a different attr such as "title" or "alt".

Hope this was helpful.

0
source

Source: https://habr.com/ru/post/1748771/


All Articles