我有一个带有以下 DOM 树的代码:
<div id="blogPagination">
<div class="pagination">
<ul>
<li>
<a href="/2" >1</a>
</li>
<li>
<a href="/3" >2</a>
</li>
</ul>
</div>
</div>
我正在尝试访问我的标签的 href。我尝试过的任何东西都无法达到它。
使用 jQuery 实现它的最佳方式是什么?
我试过:
console.log($('#blogPagination div ul > li a ').attr("href"));
console.log($('#blogPagination > a ').attr("href"));
$('#blogPagination').children('a')
console.log($('#blogPagination div ul li a').attr("href"));
没有运气..
谢谢
编辑:
在 nbrooks 的回答之后,这是我到目前为止所尝试的:
function bindPagination() {
console.log("bind");
$(function() {
var links = $("#blogPagination ul a").map(function(e) {
e.preventDefault();
return this.href;
}).get();
console.log(links);
});
编辑 2:
考虑到 Syfaro 的回答,我也尝试过:
$('#blogPagination').find('a').each(function(e) {
e.preventDefault();
console.log($(this).attr('href'));
});
没有运气。
编辑 3:我想提供有关此功能的更多详细信息,毕竟这可能会产生重大影响:
为了加载这个分页,我使用 Ajax 和把手包装到一个文档就绪函数中:
$(document).ready(function(){
// Get the customer service stats
var Content = {
init: function() {
/* this.getHomePosts(); */
this.getBlogPosts();
},
getBlogPosts: function(offset) {
if(offset == undefined){
offset = 0;
}
// GET the events with JSON
$.ajax({
type: "POST",
data: {},
url: site_url+"/main/blog/"+offset,
dataType: "json",
success: function(results) {
posts = results["posts"].map(function (blogContent) {
if( blogContent.picture != '' ) {
return {
Title: blogContent.title ,
Picture: Content.urlPostPic + blogContent.picture ,
Video: '' ,
Text: blogContent.text ,
Datetime: blogContent.datetime ,
}
} else {
return {
Title: blogContent.title ,
Picture: '' ,
Video: blogContent.video ,
Text: blogContent.text ,
Datetime: blogContent.datetime ,
}
}
});
pagination = {pagination: results["pagination"]};
var template = Handlebars.compile( $('#templateBlog').html() );
$('#blogPosts').append( template(posts) );
var template = Handlebars.compile( $('#templatePagi').html() );
$('#blogPagination').append( template(pagination) );
// Here we call bindPagination <===
bindPagination();
}
});
},
};
Content.init();
您可以在 get BlogPosts 函数中看到我调用 BindPagination 应该是这个函数,以防止默认行为并根据偏移量调用内容(分页系统)
function bindPagination() {
console.log("bind");
var links = $("#blogPagination ul a").map(function(e) {
e.preventDefault();
return this.href;
}).get();
console.log(links);
$('#blogPagination').find('a').each(function(e) {
console.log("clicked !");
e.preventDefault();
console.log($(this).attr('href'));
// var attr = this.attr();
// var id = attr.replace("/","");
// $('#blogPosts').empty();
// $('#blogPagination').empty();
// Content.getBlogPosts(id);
});
}
});
最后 }); 代表文件准备完毕。