This jQuery code loads a specific page within a div (this works):
<script type="text/javascript">
$(document).ready(function() {
$("#button2").on("click", function(){
$("#loader").load($("#button2").attr("page"));
return false;
});
});
</script>
Also, I have 2 links with an attribute "page" indicating the html file to be loaded in the div:
<li><a href="#" title="" id="button2" page="page1.html">Link 1</a></li>
<li><a href="#" title="" id="button2" page="page2.html">Link 2</a></li>
This is the div where the page is loaded:
<div id="loader"></div>
The problem is that only loads "page1.html" when I click on the first link. If I click on the second link does not load "page2.html".
I think it may be a problem of the id attribute of link "button2" on repeat maybe something happens.
What am I doing wrong?
Thank you!
You must not use same ids for elements. Each id attribute must be unique (according to HTML4.01 and HTML5 specs).
It would be better to use a class to identify these buttons instead, like this:
<script type="text/javascript">
$(document).ready(function() {
$(".buttons").on("click", function(){
$("#loader").load($(this).attr("page"));
return false;
});
});
</script>
and the button's HTML:
<li><a href="#" title="" class="buttons" page="page1.html">Link 1</a></li>
<li><a href="#" title="" class="buttons" page="page2.html">Link 2</a></li>
"What am I doing wrong?"
You are using duplicate ID's, which is forbidden in HTML. Use a class name or an element selector instead. You can refer to the currently clicked button inside the event handler by $(this)
:
<li><a href="#" title="" class="button" page="page1.html">Link 1</a></li>
<li><a href="#" title="" class="button" page="page2.html">Link 2</a></li>
$(".button2").on("click", function(){
$("#loader").load($(this).attr("page"));
return false;
});
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.