无法访问jQuery插入的元素

时间:2018-06-11 23:07:39

标签: javascript jquery input insert click

我自己做了一个小标签输入字段,但我无法使用jquery访问插入的标签。

每次点击输入时,输入字段的值将在输入之前作为<div class="chip"></div>插入。

如果我尝试点击它,它只适用于输入未插入的标签。

$('.chip').on('click', function() {
  console.log('click');
});

$('.wrap input').on('keydown', function(e) {
  var key = e.which,
      input = $(this),
      value = input.val();
	
  if(key === 13) {
    if(value != '') {
      $('<div class="chip">' + value + '</div>').insertBefore(input);
      $(input).val('');
    }
  }
});
.wrap {
  box-sizing: border-box;
  width: 80%;
  height: 55px;
  line-height: 55px;
  border: 1px solid #bebebe;
  border-radius: 28px;
  padding: 0 .5rem;
  font-size: 1rem;
  font-weight: 400;
  display: flex;
  flex-direction: row;
  align-items: center;
  overflow: auto;
}

.wrap .chip {
  font-size: 14px;
  font-weight: 300;
  background: #e6e6e6;
  border-radius: 20px;
  height: 40px;
  padding: 0 20px;
  line-height: 40px;
  margin-right: 5px;
}

.wrap input {
  box-sizing: border-box;
  height: 40px;
  line-height: 40px;
  padding: 0 1rem;
  font-size: 1rem;
  font-weight: 400;
  border: none;
  flex: 1;
}

.wrap input:focus {
  outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <div class="chip">tag1</div>
  <input type="text">
</div>

1 个答案:

答案 0 :(得分:1)

$('.wrap').on('click', '.chip', function() {
  console.log('click');
});

$('.wrap input').on('keydown', function(e) {
  var key = e.which,
      input = $(this),
      value = input.val();
	
  if(key === 13) {
    if(value != '') {
      $('<div class="chip">' + value + '</div>').insertBefore(input);
      $(input).val('');
    }
  }
});
.wrap {
  box-sizing: border-box;
  width: 80%;
  height: 55px;
  line-height: 55px;
  border: 1px solid #bebebe;
  border-radius: 28px;
  padding: 0 .5rem;
  font-size: 1rem;
  font-weight: 400;
  display: flex;
  flex-direction: row;
  align-items: center;
  overflow: auto;
}

.wrap .chip {
  font-size: 14px;
  font-weight: 300;
  background: #e6e6e6;
  border-radius: 20px;
  height: 40px;
  padding: 0 20px;
  line-height: 40px;
  margin-right: 5px;
}

.wrap input {
  box-sizing: border-box;
  height: 40px;
  line-height: 40px;
  padding: 0 1rem;
  font-size: 1rem;
  font-weight: 400;
  border: none;
  flex: 1;
}

.wrap input:focus {
  outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <div class="chip">tag1</div>
  <input type="text">
</div>

事件仅绑定到DOM中可用的元素。为了考虑新插入的dom节点,您必须将事件委托给绑定事件时可用的祖先。

更改

$('.chip').on('click', function() {
  console.log('click');
});

$('body').on('click', '.chip', function() {
  console.log('click');
});

body可以替换为绑定时DOM中最近的祖先。