如何从同一div中的外部页面加载链接
Need help..
I have an index.php
page. On that page, I have a link to page-2.php
.
On page-2.php
,
i also have a link to other page. May I know how to load the link on page-2.php
in a same div on index.php
page.
I'm using jQuery load method do to this. I'm able to load page-2.php
inside a div
on index.php
. Below are the codes that I made.
$(document).ready(function() {
$('a#staff_info').click(function(e){ //link to page-2.php
e.preventDefault();
var page = $(this).attr('href');
$('#content').load(page);
$('a#upd_staff').click(function(){ //link on page2.php
var page_info = $('a#upd_staff').attr('href');
$('#content').load(page_info);
});
});
});
the above code will direct me to a new page not on a same div
需要帮助.. p>
我有一个 在 我还有一个指向其他页面的链接。 我是否知道如何在 I 我正在使用jQuery load方法做到这一点。 我可以在 上面的代码会将我引导到一个不在同一个div上的新页面
div> index.php code>页面。 在该页面上,我有一个指向
page-2.php code>的链接。 p>
page-2.php code>, p>
page.php code>页面上的同一div中加载
page-2.php code>上的链接。 p>
index.php code>上的
div code>中加载
page-2.php code>。 以下是我制作的代码。 p>
$(document).ready(function(){
$('a#staff_info')。click(function(e){// link to page-2 .php
e.preventDefault();
var page = $(this).attr('href');
$('#content')。load(page);
$('a#upd_staff ').click(function(){// link on page2.php
var page_info = $('a#upd_staff')。attr('href');
$('#content')。load(page_info );
});
});
});
code> pre>
Ajax is asynchronous.
$('#content').load(page);
The above starts loading page two
$('a#upd_staff').click(function(){ //link on page2.php
Then you try to bind your event handler to content from page 2 before it is has finished loading.
So when you click on the link, there is no JS bound to it, so it acts as a normal link.
Use deferred event handlers (so they listen on the document and check what element was clicked when the click happens).
$(document).ready(function() {
function ajaxLoad(event) {
event.preventDefault();
var page = $(this).attr('href');
$('#content').load(page);
}
$(document).on("click", "a#staff_info, a#upd_staff", ajaxLoad);
});
You can use get()
for add directly on your div:
$(document).ready(function() {
$('a#staff_info').click(function(e){ //link to page-2.php
e.preventDefault();
var page = $(this).attr('href');
$.get(page, function(data, status){
//action on page loaded, data is your page result
$('#content').html(data)
});
$('a#upd_staff').click(function(){ //link on page2.php
var page_info = $('a#upd_staff').attr('href');
$('#content').load(page_info);
});
});
});
when you click on $('a#staff_info')
this -- I can see that you use e.preventDefault();
for preventing the normal action of the anchor tag but when you click on $('a#upd_staff')
this you did not use e.preventDefault();
-- that's why this redirect to page2.php
. Use e.preventDefault();
- this for next one click may be this will help you