切换 contenteditable 属性
switch contenteditable attr
为什么行 obj.attr(b, 'false').blur();
不起作用?这里有什么问题?
$('#btnren').on('click', function() {
let obj = $('#cptitlea');
let b = 'contenteditable';
if (obj.attr(b, 'false')) {
obj.attr(b, 'true').focus(); // this works
} else {
obj.attr(b, 'false').blur(); // doesn't work
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cptitlea'>323</div>
<br>
<button id='btnren'>CLICK</button>
问题是因为您在 if
语句中使用了 attr()
的 setter。这意味着您的 if
实际上是在说 'if (jQuery object exists)',它始终是 true
。
要解决此问题,请使用 attr()
的 getter 检索值并在 if
语句中使用它。请注意,您可以通过向 attr()
提供一个函数来简化逻辑,其中 returns 将根据当前值设置新值。试试这个:
$('#btnren').on('click', function() {
let $el = $('#cptitlea');
let b = 'contenteditable';
$el.attr(b, function(i, v) {
return v === 'true' ? false : true;
}).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cptitlea'>323</div>
<br>
<button id='btnren'>CLICK</button>
为什么行 obj.attr(b, 'false').blur();
不起作用?这里有什么问题?
$('#btnren').on('click', function() {
let obj = $('#cptitlea');
let b = 'contenteditable';
if (obj.attr(b, 'false')) {
obj.attr(b, 'true').focus(); // this works
} else {
obj.attr(b, 'false').blur(); // doesn't work
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cptitlea'>323</div>
<br>
<button id='btnren'>CLICK</button>
问题是因为您在 if
语句中使用了 attr()
的 setter。这意味着您的 if
实际上是在说 'if (jQuery object exists)',它始终是 true
。
要解决此问题,请使用 attr()
的 getter 检索值并在 if
语句中使用它。请注意,您可以通过向 attr()
提供一个函数来简化逻辑,其中 returns 将根据当前值设置新值。试试这个:
$('#btnren').on('click', function() {
let $el = $('#cptitlea');
let b = 'contenteditable';
$el.attr(b, function(i, v) {
return v === 'true' ? false : true;
}).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cptitlea'>323</div>
<br>
<button id='btnren'>CLICK</button>