我有这个页面,第一个按钮工作正常。
我想在按第二个按钮时给我 href 中的链接,我尝试了这样的操作,但我得到了整个页面,而不仅仅是链接的值,为什么?
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url = "http://localhost/test/asdfasdf.php";
$("#button").on("click", function() {
$('body').load( url );
});
$("#button2").on('click',function(){
$('body').load( url +"#link" );
});
});
</script>
</head>
<body>
<input type="button" id="button" value="load" />
<input type="button" id="button2" value="search for a tag" />
</body>
</html>
最佳答案
我想你想要一个空间:
$('body').load(url + " #link");
http://api.jquery.com/load/#loading-page-fragments
您似乎想要的只是 href
a#link
的该 URL 处的元素。因此,不要将其加载到<body>
中,只需发出AJAX请求,然后查看结果:
$.ajax({
type: "GET",
url: "http://localhost/test/asdfasdf.php",
dataType: "html"
}).done(function (data) {
var the_link = $(data).find("#link");
alert(the_link.attr("href"));
});
并输入 href
在 <body>
,将此行添加到 .done()
中方法:
$("body").html(the_link.attr("href"));
// or
$("body").append(the_link.attr("href"));
但是如果你真的想加载a#link
元素进入 <body>
,执行之前的操作,然后查找 a#link
元素并获取其属性:
$('body').load(url + " #link", function () {
var the_link = $("#link");
alert(the_link.attr("href"));
});
关于javascript - 加载页面片段时 jQuery load(URL) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15710861/