甚至是.length的Listener

时间:2016-10-01 20:39:00

标签: javascript jquery html

目前我有一个计算文档中类的数量的脚本,但是,我使用另一个jquery脚本来删除'。删除'单击时的类,但.alerts计数保持不变。我假设这是因为文档需要一个事件监听器,但似乎无法使其正常工作。

html -

<!DOCTYPE html>

<html lang = "en">

	<head>
		<title>Testsite</title>
		<link rel="stylesheet" type="text/css" href="./css/main.css">
		<script src ="./js/search.js"></script>
		<script type="text/javascript" src="js/jquery.min.js"></script>
	</head>

	<body">


<!-- SEARCH BAR -->
	<div id="searchdisappear" style="display:block;">
	<center><h1> INTEREST SEARCH </h1></center>
			<input class="interestsearch" id="searchbox" maxlength="200" type="text" title="Search for an interest" onkeyup="autocomplet();" autocomplete="off" onkeypress="enterPressed(event, searchbox);" placeholder="Search for an interest.."/>
		<div class="input_container">
		<ul id="interest_list_id"></ul>
		</div>
	</div>
	
<!-- CONNECTING PEOPLE WITH SAME INTEREST-->
		<div id="searching" style="display:none;">
			<center> <p>Finding people..</p></center>
		</div>

</html>

它显示正确的金额,但是当他们被jquery删除时不会改变,任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以使用MutationObserver来观察对DOM的修改。见下面的例子:

function updateCount() {
  $(".counter").eq(0).html($("ul > .alert").length);
}
$(document).ready(function() {
  MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

  var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    updateCount();
    // ...
  });
  var ul = $('#alertList');
  // define what element should be observed by the observer
  // and what types of mutations trigger the callback
  observer.observe(document.getElementById('alertList'), {
    subtree: true,
    attributes: true,
    childList: true
      //...
  });
});
$('#addLi').click(function() {
  $('#alertList').append('<li class="alert"></li>');
});
//allow removing items by clicking on them
$('.alert').click(function(event) {
    $(this).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="alertList">
  <li class="alert"></li>
  <li class="alert"></li>
  <li class="alert"></li>
</ul>

<button id="addLi">Add Item</button>
<div class="counter">3</div>

答案 1 :(得分:2)

您可以调用一个函数,在删除元素时更新元素的当前.length

&#13;
&#13;
$(function() {

  function count() {
    $(".counter").html($(".alert").length)
  }

  count();

  $(".alert").click(function() {
    $(this).remove();
    count();
  });

  $("button").click(function() {
    $(".alert").eq(+$(this).prev("input").val()).remove();
    $(this).prev("input").attr("max", $(".alert").length)
    .val($(".alert").length -1)
    count()
  })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="alert">click</li>
  <li class="alert">click</li>
  <li class="alert">click</li>
</ul>

<div class="counter"></div>
<input type="number" min="0" max="2" value="2">
<button>remove alert</button>
&#13;
&#13;
&#13;