load page according to class names
-
16-09-2019 - |
Question
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).
OTHER TIPS
For XHTML valid document, the easiest is to add invisible child DIV under your main DIV. E.g.:
<div class="item">
<div class="variable type">item_wall</div>
<div class="variable id">1</div>
</div>
You can find the "custom attribute" using .find(). E.g.:
$(".item").click(function() {
var type = $(this).find(".type").val();
var url = "something.php?type=" + type;
windows.location = url;
});
A bit of opinion: mixing data with UI should be avoided.