Reputation: 1001
I got a script for loading a html files to my page. Everything is work, but i want a something like "loop" to load every position in my list.
So i got a script
<script>
$(document).ready(function(){
$("#introduction").click(function(){
$("#main_info").load("introduction.html");
});
});
</script>
And I load a position from menu "introduction.
<ul>
<li><a href="#" id="home"><i class="home"></i>home</a></li>
<li><a href="#" id="introduction"><i class="introduction"></i>introduction</a></li>
<li><a href="#" id="structure"><i class="structure"></i>structure</a></li>
</ul>
But how to change this script for try use every position in my UL LI A?
like when i click a li with home i will load home.html, introduction = introduction.html and structure = structure.html??
Upvotes: 1
Views: 37
Reputation: 14853
You can achieve this "loop" logic using .each()
from JQuery
just like that:
$(document).ready(function(){
$('ul li a').each(function() { // <-- Iterate throught all your links
$(this).click(function(){
var fileToLoad = $(this).attr('id') + '.html';
$("#main_info").load(fileToLoad);
});
});
});
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<ul>
<li><a href="#" id="home"><i class="home"></i>home</a></li>
<li><a href="#" id="introduction"><i class="introduction"></i>introduction</a></li>
<li><a href="#" id="structure"><i class="structure"></i>structure</a></li>
</ul>
Upvotes: 1
Reputation: 4004
Try:
$("a").click(function (){
$(this).find("i").load($(this).attr("id")+".html");
});
Upvotes: 2