JQuery:单击时更改动态创建的<li>元素的类

时间:2017-02-06 15:12:59

标签: javascript jquery html css twitter-bootstrap

当用户键入时,文本将变为数组,以“”分隔。对于数组的每个成员,<ul>元素由一个<li>创建并占用,每个元素包含其各自的单词。默认情况下,这些类被赋予类list-group-item-danger,如Bootstrap中所示。 点击后,应删除此类并替换为list-group-item-success

有一个默认的<ul>元素。其中的<li>成员按预期响应,单击时颜色会发生变化。但是,一旦删除这些元素并插入动态创建的<li>元素,它们就不再起作用并保留在它们已有的list-group-item-danger类中。

HTML:

<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 col-lg-offset-1">
                <div class="input-group">
                    <input id="wordsearch" type="text" class="form-control wordsearch" placeholder="" />                      
                    <span id="go" class="input-group-btn">
                        <button class="btn btn-default" type="submit">
                            <span class="glyphicon glyphicon-search"></span>
                        </button>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div id="wordFilter">
        <ul class="list-group word-filter">
            <li class="list-group-item list-group-item-danger">Your</li>
            <li class="list-group-item list-group-item-danger">words</li>
            <li class="list-group-item list-group-item-danger">appear</li>
            <li class="list-group-item list-group-item-danger">here</li>
            <li class="list-group-item list-group-item-danger">as</li>
            <li class="list-group-item list-group-item-danger">you</li>
            <li class="list-group-item list-group-item-danger">type.</li>
        </ul>
    </div>
</div>

CSS:

.word-filter li{
    display: inline;
}

的JQuery:

$(document).ready(function() {
    $('#wordsearch').keyup(function() {
        var inputVal = $('#wordsearch').val();
        var inputs = inputVal.split(" ");
        var ul = document.createElement("ul");
        ul.setAttribute("class", "list-group word-filter");
        $(inputs).each(function() {
            var li = document.createElement("li");
            li.setAttribute("class", "list-group-item list-group-item-danger");
            li.appendChild(document.createTextNode(this));
            ul.appendChild(li);
        });
        $('#wordFilter').empty();
        $('#wordFilter').append(ul);
    });
/* Colour Switching Function */
    $('div#wordFilter ul li').click(function() {
        if($(this).hasClass('list-group-item-success')) {
            $(this).addClass('list-group-item-danger');
            $(this).removeClass('list-group-item-success');
        } else {
            $(this).addClass('list-group-item-success');
            $(this).removeClass('list-group-item-danger');
        }
    });
});

3 个答案:

答案 0 :(得分:1)

考虑使用on()函数来处理动态创建元素的连线事件:

// This will handle any current and future click events
// for elements that match this selector
$('#wordFilter').on('click','ul li', function() {
    // Equivalent code to your previous statements
    $(this).toggleClass('list-group-item-success list-group-item-danger');
});

click()函数的操作与此不同,只会为事件调用时当前存在的事件连接事件。

答案 1 :(得分:1)

由于您的li元素已动态添加到DOM,因此您应使用事件委派 .on() ,(我建议使用jQuery {{3 }} 方法):

$('body').on('click', '#wordFilter ul li', function() {
    $(this).toggleClass('list-group-item-success list-group-item-danger');
});

希望这有帮助。

$(document).ready(function() {
  $('#wordsearch').keyup(function() {
    var inputVal = $('#wordsearch').val();
    var inputs = inputVal.split(" ");
    var ul = document.createElement("ul");
    ul.setAttribute("class", "list-group word-filter");

    $(inputs).each(function() {
      var li = document.createElement("li");
      li.setAttribute("class", "list-group-item list-group-item-danger");
      li.appendChild(document.createTextNode(this));
      ul.appendChild(li);
    });
    $('#wordFilter').empty();
    $('#wordFilter').append(ul);
  });


  $('#wordFilter').on('click', 'li', function() {
    $(this).toggleClass('list-group-item-success list-group-item-danger');
  });
});
.word-filter li {
  display: inline;
}
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="jumbotron">
  <div class="container">
    <div class="row">
      <div class="col-lg-10 col-lg-offset-1">
        <div class="input-group">
          <input id="wordsearch" type="text" class="form-control wordsearch" placeholder="" />
          <span id="go" class="input-group-btn">
            <button class="btn btn-default" type="submit">
              <span class="glyphicon glyphicon-search"></span>
            </button>
          </span>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="container">
  <div id="wordFilter">
    <ul class="list-group word-filter">
      <li class="list-group-item list-group-item-danger">Your</li>
      <li class="list-group-item list-group-item-danger">words</li>
      <li class="list-group-item list-group-item-danger">appear</li>
      <li class="list-group-item list-group-item-danger">here</li>
      <li class="list-group-item list-group-item-danger">as</li>
      <li class="list-group-item list-group-item-danger">you</li>
      <li class="list-group-item list-group-item-danger">type.</li>
    </ul>
  </div>
</div>

答案 2 :(得分:1)

您可以通过选择文档并使用.on()方法来委派活动。为了确定点击了哪个<li>,您可以使用event.target。我还使用.toggleClass()

更改了您的类方法,将其缩小到一行
/* Colour Switching Function */
  /* By selecting the document and using .on() method...
  || ...the document will listen for clicks instead of individual <li>
  || Using the capture, target, and bubbling event phases, you can...
  || use the Event Object's .target property. The event.target...
  || property will determine the actual element that you clicked...
  || ...thereby the callback will act on the correct <li>.
  */
  // Instead of changing classes with add/removeClass() use toggleClass()

  $(document).on('click', function(e) {
    var tgt = e.target;
    $(tgt).toggleClass('list-group-item-success list-group-item-danger');
  });

<强>段

$(document).ready(function() {
  $('#wordsearch').keyup(function() {
    var inputVal = $('#wordsearch').val();
    var inputs = inputVal.split(" ");
    var ul = document.createElement("ul");
    ul.setAttribute("class", "list-group word-filter");
    $(inputs).each(function() {
      var li = document.createElement("li");
      li.setAttribute("class", "list-group-item list-group-item-danger");
      li.appendChild(document.createTextNode(this));
      ul.appendChild(li);
    });
    $('#wordFilter').empty();
    $('#wordFilter').append(ul);
  });
  
  /* Colour Switching Function */
  $(document).on('click', function(e) {
    var tgt = e.target;
      $(tgt).toggleClass('list-group-item-success list-group-item-danger');


  });
});
.word-filter li {
  display: inline;
}
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="jumbotron">
  <div class="container">
    <div class="row">
      <div class="col-lg-10 col-lg-offset-1">
        <div class="input-group">
          <input id="wordsearch" type="text" class="form-control wordsearch" placeholder="" />
          <span id="go" class="input-group-btn">
                        <button class="btn btn-default" type="submit">
                            <span class="glyphicon glyphicon-search"></span>
          </button>
          </span>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="container">
  <div id="wordFilter">
    <ul class="list-group word-filter">
      <li class="list-group-item list-group-item-danger">Your</li>
      <li class="list-group-item list-group-item-danger">words</li>
      <li class="list-group-item list-group-item-danger">appear</li>
      <li class="list-group-item list-group-item-danger">here</li>
      <li class="list-group-item list-group-item-danger">as</li>
      <li class="list-group-item list-group-item-danger">you</li>
      <li class="list-group-item list-group-item-danger">type.</li>
    </ul>
  </div>
</div>