来自AJAX请求时,toggleClass不起作用

时间:2017-05-04 04:28:02

标签: javascript jquery ajax

我有一个网页,其中包含发出AJAX请求的链接。当以下.js返回时,toggleClass函数不起作用。

$(document).ready(function(){
  $("td").click(function(){
    $(this).toggleClass("br");
  });
});

如果我用toggleClass("br")之类的内容替换addClass("br"),那么确实有效。

此外,如果我将.js放入html页面或者从控制台运行它,toggleClass工作正常。似乎有关toggleClass和AJAX请求的内容一起阻止了这些代码的工作,但我对于为什么会这样做没有任何地球上的想法。

更新

我已经找到了问题所在。我不小心把jQuery包含了两次,因此来自AJAX请求的javascript正在运行两次。因此,toggleClassaddClass时,只有removeClass“无效”的原因。

唯一的谜团是为什么只有当.js来自AJAX请求而不是HTML本身时才会出现这种情况。

2 个答案:

答案 0 :(得分:0)

假设您希望import java.util.ArrayList; import java.util.HashSet; public class Main { public static void main(String[] args) { //Sample Word String word = "Tomorrow-Today"; //Sample Letters for permutation String rule_char_set = "tw"; ArrayList<Character> test1 = lettersFound(word, rule_char_set); printPermutations(test1); } public static void printPermutations(ArrayList<Character> arrayList) { char[] chars = new char[arrayList.size()]; int charIterator = 0; for(int i=0; i<arrayList.size(); i++){ chars[i] = arrayList.get(i); } for (int i = 0, n = (int) Math.pow(2, chars.length); i < n; i++) { char[] permutation = new char[chars.length]; for (int j =0; j < chars.length; j++) { permutation[j] = (isBitSet(i, j)) ? Character.toUpperCase(chars[j]) : chars[j]; } System.out.println(permutation); } } public static boolean isBitSet(int n, int offset) { return (n >> offset & 1) != 0; } public static ArrayList<Character> lettersFound(String word, String rule_char_set) { //Convert the two parameter strings to two character arrays char[] wordArray = word.toLowerCase().toCharArray(); char[] rule_char_setArray = rule_char_set.toLowerCase().toCharArray(); //ArrayList to hold found characters; ArrayList<Character> found = new ArrayList<Character>(); //Increments the found ArrayList that stores the existent values. int foundCounter = 0; for (int i = 0; i < rule_char_setArray.length; i++) { for (int k = 0; k < wordArray.length; k++) { if (rule_char_setArray[i] == wordArray[k]) { found.add(foundCounter, rule_char_setArray[i]); foundCounter++; } } } //Convert to a HashSet to get rid of duplicates HashSet<Character> uniqueSet = new HashSet<>(found); //Convert back to an ArrayList(to be returned) after filtration of duplicates. ArrayList<Character> filtered = new ArrayList<>(uniqueSet); return filtered; } } 处理程序位于由AJAX查询填充的元素上,您必须将事件绑定到AJAX查询触发之前存在的DOM元素。我们假设你有以下HTML:

click

...而且你知道你将通过AJAX填充表格。然后我们需要声明我们的jQuery选择器:

<html>
  <body>
    <table id="populatedByAjax"></table>
  </body>
</html>

这可确保$("#populatedByAjax").on("click", "td", function(){ $(this).toggleClass("br"); }); 事件绑定到选择器click

中的任何当前或未来td元素

答案 1 :(得分:0)

使用委派事件将click事件绑定到动态创建的元素,并避免频繁附加和删除事件处理程序。

$(document).on('click', '#td', function() {
  $(this).toggleClass("br");
});