JQUERY.列出学徒
JQUERY. list apprenticer
但我似乎无法让它工作。
这是我的代码:
$(document).ready(function() {
$("#theUL").on('click', 'li', function () {
if ($(this).css('textDecoration') == 'lineunder') {
$(this).css('textDecoration', 'none');
} else {
$(this).css('textDecoration', 'lineunder');
}
});
});
使用 toggleClass 在元素中添加或删除类。这将减少代码中的行数
$(document).ready(function() {
$("#theUL").on('click', 'li', function() {
$(this).toggleClass('colorText')
});
});
.colorText {
text-decoration: line-through;
color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="theUL">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
你的代码不起作用,因为当你用文本修饰的jQuery获取CSS属性时,它也返回颜色。如果要使用此属性,则还应在 if 中添加颜色检查。这应该可以满足您的需求:
$(document).ready(function() {
$("#theUL").on('click', 'li', function () {
if ($(this).css('text-decoration') == 'line-through solid rgb(0, 0, 0)') {
$(this).css('text-decoration', 'none');
} else {
$(this).css('text-decoration', 'line-through');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="theUL">
<li>First</li>
<li>Second</li>
</ul>
顺便说一下,你可以使用CSS类更轻松,更干净,而不是以这种方式更改样式
$(document).ready(function() {
$("#theUL li").on('click', function () {
if ($(this).css('text-decoration') == 'line-through') {
$(this).css('text-decoration', 'none');
} else {
$(this).css('text-decoration', 'line-through');
}
});
});
这个上下文中的这个是UL,如果你使用上面的代码,你确保它是上下文中的这个
两件事:
- 更改选择器以直接访问
li
元素。 - 您的
line-through
测试将永远不会满足,因为该属性包含的不仅仅是这些。
$(document).ready(function() {
$("#theUL > li").on('click', function () {
// The `text-decoration` CSS property contains more than just 'line-through'
console.log($(this).css('text-decoration'));
if ($(this).css('text-decoration') == 'line-through solid rgb(0, 0, 0)') {
$(this).css('text-decoration', 'none');
} else {
$(this).css('text-decoration', 'line-through');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="theUL">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
您需要
将 if 语句条件更改为:
if ($(this).css('text-decoration') == 'line-through solid rgb(0, 0, 0)') {
...
}
使用 $(this).css('text-decoration', 'line-through')
设置 CSS 将在后台执行一些操作,因为默认 CSS 项仍在设置,例如实线和颜色。