为什么replaceWith取消对其变量的调用

Why does replaceWith cancels calls to its variable?

本文关键字:变量 调用 replaceWith 取消 为什么      更新时间:2023-09-26

我正在尝试克隆dom元素并更改它们的标记。但是在我替换主元素之后,我不能更改它的子元素,也不能应用一些点击事件。

我评论了一行,之后它就停止工作了。谢谢你的帮助!

http://codepen.io/sanns/pen/eJvzBN?editors=101

var selectDom = $('select');
selectDom.each(function() {
  var clone = $(this).clone().insertAfter(this);
  //take classes from clone
  var classesStr = clone.attr('class');
  clone = clone.replaceWith(function(index, oldHTML) {
    return $('<div class="custom-select ' + classesStr + '">').html(oldHTML);
  });
//why does not work?
  clone.find('option').replaceWith(function(index, oldHTML) {
    return $('<li>').html(oldHTML);
  });
  clone.wrapInner('<ul class="scrollbox"></ul>').prepend('<span class="shower"> Выберитеtttttttttteeeee тратататататат</span>');

  //BEHAVIOR SELECT
  clone.on('click', function() {
    alert('asdf');
  });
});

实际上.replaceWith()返回原始的jQuery object,而不是用某些东西替换。

您可以找到更多详细信息:http://api.jquery.com/replacewith/

下面是一个小例子:

$( "button" ).click(function() {
  $( this ).replaceWith( "<div>" + $( this ).text() + "</div>" );
});
button {
    display: block;
    margin: 3px;
    color: red;
    width: 200px;
  }
  div {
    color: red;
    border: 2px solid blue;
    width: 200px;
    margin: 3px;
    text-align: center;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>First</button>
<button>Second</button>
<button>Third</button>