jquery - 动态创建的内联样式的 JQuery 测试
问题描述
我有一个元素,它调用一个函数来创建内联style
属性。这个:
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities"
onclick="highlightEntities(this)">Guilhem Vidal</li>
...称之为:
function highlightEntities(element) {
$(element).css("backgroundColor", "yellow");
$("."+ element.id).css("backgroundColor", "yellow");
}
它为自己(和许多其他元素)设置背景颜色并且完美地工作。
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities"
onclick="highlightEntities(this)" style="background-color: yellow;">Guilhem Vidal</li>
现在,当用户再次单击它时,我想测试它是否已经设置了样式。这应该很简单:如果style
已设置内联,则删除样式,如果没有style
,则创建一个。
但是我的测试尝试似乎没有做任何事情:
function highlightEntities(element) {
var attr = ($(element).attr("style")
if(typeof attr !== undefined && attr !== false) {
$(element).removeAttr("style");
$("."+ element.id).removeAttr("style");}
else {
$(element).css("backgroundColor", "yellow");
$("."+ element.id).css("backgroundColor", "yellow");}
}
看看测试一个属性带来的各种问题,我可能没有正确测试?
可能会提前感谢。
解决方案
typeof
返回 a String
,因此您的测试应该是:
if (typeof attr !== "undefined" && attr !== false)
否则,第一个子句总是评估为真!
这是一个片段,显示此修复使原始功能正常工作:
function highlightEntities(element) {
var attr = $(element).attr("style");
if(typeof attr !== "undefined" && attr !== false) {
$(element).removeAttr("style");
$("."+ element.id).removeAttr("style");}
else {
$(element).css("backgroundColor", "yellow");
$("."+ element.id).css("backgroundColor", "yellow");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities"
onclick="highlightEntities(this)">Guilhem Vidal</li>
</ul>
<div class="Guilhem_Vidal_MSP-AU">Other element with class matching trigger id</div>
但是,正如@Taplar 所述,推荐的方法是使用 jQuerytoggleClass()
或ES6classList.toggle
。
请注意,jQuerytoggleClass
更广泛地与旧浏览器兼容。您可以在此处classList
查看支持。
这是一个有和没有 jQuery的解决方案:
// Vanilla Javascript
function highlightEntities(element) {
element.classList.toggle("highlighted");
document.querySelectorAll("." + element.id).forEach( e => e.classList.toggle("highlighted") );
}
// jQuery
function jqHighlightEntities(element) {
$(element).toggleClass("highlighted");
$("." + element.id).toggleClass("highlighted");
}
.highlighted {
background-color: yellow;
}
<ul>
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities"
onclick="highlightEntities(this)">Guilhem Vidal</li>
</ul>
<div class="Guilhem_Vidal_MSP-AU">Other element with class matching trigger id</div>
推荐阅读
- swift - 为什么我的自定义 UIButton 在我的 Xcode 项目中出现扭曲并带有两个边框?
- c++ - BOOST 平面遍历未正确访问外边缘
- java - 如何序列化由Java中其他自定义类组成的对象
- python - Pandas 通过多个条件返回列的值?
- c# - 如何使用标签助手将整个模型传递给部分视图
- python - 无法将“sys.executable”路径与另一个文件连接
- python-3.x - 如何在 OpenCV 中屏蔽图像。然后将图像反转成二进制数组
- postgresql - Postgresql pg_basebackup 和 archive_command
- javascript - 模态表单标签标签中的引导工具提示不起作用
- sphinx - Manticore - JSON 的 FACET,使用 JSON 数组的键