简体   繁体   中英

load part of a page with jquery/ajax/javascript

I have a series of links that will load a section of another page into my main page container #pageCont . I am using the script below and it works perfectly, but only on the first link, the 2nd and 3rd links just redirect me to the actual pages. I am new to jquery and ajax so i don't have any idea how to go on with this code.

 $("#embed-uri").on("click", (function(e){ $.ajax({ url:$(this).attr("href"), success: function(response) { $("#pageCont").html($(response).find("#target")); } }); e.preventDefault(); })); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id"pageCont" class="main"> </div> <div class="sidebar"> <li><a id="embed-uri" href="/webpage1/"</a></li> <li><a id="embed-uri" href="/webpage2/"</a></li> <li><a id="embed-uri" href="/webpage3/"</a></li> </div> 

.

Kindly use class instead of same id's like this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id"pageCont" class="main">
</div>
<div class="sidebar">
<div><a class="embed-uri" href="/webpage1/"</a></div>
<div><a class="embed-uri" href="/webpage2/"</a></div>
<div><a class="embed-uri" href="/webpage3/"</a></div>
</div>

$(".embed-uri").on("click", (function(e){
$.ajax({
url:$(this).attr("href"),
success: function(response) {
$("#pageCont").html($(response).find("#target"));
}
});

e.preventDefault();
}));

Use class for an "a" tag instead of id then change the "#" selector to ".". It should work like a charm

You have trouble with your selector) Replace id with class. Like that)

 $(".embed-uri").on("click", (function(e){ $.ajax({ url:$(this).attr("href"), success: function(response) { $("#pageCont").html($(response).find("#target")); } }); e.preventDefault(); })); <!-- begin snippet: js hide: false console: true babel: false --> 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id"pageCont" class="main"> </div> <div class="sidebar"> <li><a class="embed-uri" href="/webpage1/"</a></li> <li><a class="embed-uri" href="/webpage2/"</a></li> <li><a class="embed-uri" href="/webpage3/"</a></li> </div> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM