Search code examples
jqueryclass-names

load page according to class names


I've got code like this on my page:

<div class="item item_wall id1"></div>
<div class="item item_wall id2"></div>
<div class="item item_wall id3"></div>
<div class="item item_wall id4"></div>
<div class="item item_wall id5"></div>

I want something in jquery so that when a div with the class of "item" is clicked, it will load another div from a page, the page's filename will depend on the div clicked. Preferably i would like it to load:

something.php?type=item_wall&id=id1

For future reference this is what I ended up with:

<div id="itemstable" class="item_love">
    <div class="id1"></div>
    <div class="id2"></div>
    <div class="id3"></div>
    <div class="id4"></div>
    <div class="id5"></div>
    <div class="id6"></div>
</div>

jQuery:

<script>
$("#itemstable div").click(function(){
    var url = "something.php?type=" + $(this).parent().attr("class") + "id=" + $(this).attr("class");
    alert(url);
}); 
</script>

Solution

  • Echoing Spencer Ruport's answer, you can make this easier when using jQuery to use custom attributes other than class.

    For example, your DIV may look like this:

    <div class="item" type="item_wall" id="1"></div>
    

    You can easily create jQuery selector and event like the following:

    $(".item").click(function() {
        var url = "something.php?type=" + $(this).attr("type");
        windows.location = url;
    });
    

    Of course, don't forget to check for validity, never trust user input (your HTML can be rewrote by a malicious user).