我想替换 <fieldset>
进入<div>
如果字段集中没有 input
.我正朝着这个方向前进,但在完成它时遇到了问题。
(function ($) {
const selector = {
fieldsetWrapper: '.fieldsetWrapperClass',
radioWrapper: '.class-for-radio-input'
};
class FieldsetReplace {
constructor(element) {
this.$fieldsetWrapper = $(element);
this.$fieldsetWrapper= this.$fieldsetWrapper.find(selector.fieldset);
this.replaceFieldset();
}
replaceFieldset() {
if (!this.fieldsetWrapper.has("input")) {
$('fieldset', this).replaceWith(function(){
return $("<div />").append($(this).contents());
});
}
}
}
最佳答案
在您提供的代码中,带有 $('fieldset', this)
的行将您的 FieldsetReplace
实例传递给 jQuery,它不知道如何处理它.您似乎还缺少一个 selector.fieldset
值,但我认为这可能只是您的代码片段中的错字。
我已将您的代码简化为以下代码段中与您的问题具体相关的部分。看起来您只是很难理解 JavaScript 中的 this
关键字。在 jQuery 方法中,this
通常表示 jQuery 对象中的单个元素。但是,除此之外,它的运作方式非常不同。
有关this
的更多信息,请随时在评论中提问或参阅 MDN 文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
const replaceFieldsetsWithoutInput = function (elementOrSelector) {
const $fieldsets = $(elementOrSelector).find('fieldset:not(:has(input))')
$fieldsets.replaceWith(function() {
return $('<div />').append($(this).contents())
})
}
replaceFieldsetsWithoutInput('.js-fieldset-wrapper')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js-fieldset-wrapper">
<!-- Unaffected - has an input -->
<fieldset>
<input value="test 1" />
</fieldset>
<!-- Should be replaced with a <div> -->
<fieldset>Test 2</fieldset>
<!-- Should also be replaced with a <div>, different contents -->
<fieldset>Test 3</fieldset>
</div>
关于javascript - 如果包装器包含特定元素,则替换 HTML 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52991195/