我尝试使用jQuery
向列表项添加click
函数。我使用JS和onClick()
使用此方法,但是我尝试使用jQuery
使代码更新。所以我的清单有以下结构:
<ul id="paginationList" class="pagination">
<li id="1" class="page-item disabled">
<a class="page-link" href="#">Previous</a>
</li>
<li class="page-item">
<a class="page-link" href="#">1</a>
</li>
<li id="2" class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>
jQuery
函数位于document.read函数:
$(function () {
$('ul.pagination li.page-item').click(function () {
var $li = $(this);
$.ajax({
type: 'GET',
url: '/Projects/ProjectTable/CountProjects',
data: { searchString: $('#searchBox').val() },
success: function(result) {
$('#table-container').load('/Projects/ProjectTable/TestPartialView',
{
searchString: $('#searchBox').val(),
currentPage: page,
projectCount: result
}, function() {
$li.addClass('active');
});
}
});
});
getTable();
});
getTable()
正在执行,但是当我点击任何<li>
时,该方法未被调用。我尝试从ul.pagination
电话中移除.click
,但又一次没有影响。
我需要更改哪些内容,以便<li>
对每个方法都有.click
方法?
我检查过控制台,根本没有报告任何错误。
答案 0 :(得分:1)
您的代码存在一些问题。
似乎你永远不会删除“禁用”类,即使你添加“活动”类(但也许这就是你想要的),并且你没有使用event delegation所以也许你的甚至在创建<li>
元素之前绑定。
$('.pagination').on("click", ".page-item", function(){
console.log(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="paginationList" class="pagination">
<li id="1" class="page-item disabled">
<a class="page-link">Previous</a>
</li>
<li class="page-item">
<a class="page-link">1</a>
</li>
<li id="2" class="page-item">
<a class="page-link">Next</a>
</li>
</ul>
$(()=>{
$('.pagination').on("click", ".page-item", onPaginationItemClick);
function onPaginationItemClick(){
var listItem = this,
// it's nicer to assign jQuery ajax calls to a variable, so it could be aborted if needed
CountProjects_REQ = $.ajax({
type : 'GET',
url : '/Projects/ProjectTable/CountProjects',
data : { searchString: $('#searchBox').val() }
});
// using the "done()" method on the jQuery XHR object. do not use "success", it is the old and aweful way
CountProjects_REQ.done(RES => {
$('#table-container').load('/Projects/ProjectTable/TestPartialView', {
searchString : $('#searchBox').val(),
currentPage : page,
projectCount : RES
}, ()=>{
listItem.classList.add('active');
});
})
};
// I have no idea what this part is for...I'll just leave it here
getTable();
});
答案 1 :(得分:0)
$('ul.pagination li.page-item')
适用于click
事件:
$('ul.pagination li.page-item').click(function () {
console.log('clicked');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="paginationList" class="pagination">
<li id="1" class="page-item disabled">
<a class="page-link" href="#">Previous</a>
</li>
<li class="page-item">
<a class="page-link" href="#">1</a>
</li>
<li id="2" class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>
&#13;
如果您动态添加li
,那么您可以更好地使用
$(document).on('click', 'ul.pagination li.page-item', function () {
console.log('clicked');
});