我正在尝试建立无序的成分列表。点击后,一个成分(<li>
)应该使其background-color
变为黄色。
使用以下代码,我可以点击成分并更改背景颜色。但是,我无法定位单个元素。如何点击,只有<li>
的背景颜色发生了变化?
$('#lili>li').click(function () {
$('li').css('background-color', 'yellow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ingred">
<h3>INGREDIENTS</h3>
<ul id="lili">
<li>3 Tbsp soy sauce</li>
<li>1 teaspoon brown sugar</li>
<li>1 Tbsp olive oil</li>
<li>2/3 cup diced red onion</li>
<li>2/3 cup diced red bell pepper</li>
<li>2 cloves garlic, minced</li>
<li>1-inch piece of ginger, grated</li>
<li>3 eggs, well beaten</li>
<li>4 cups day old cooked white rice (from about 2 cups of raw rice)</li>
<li>1 cup frozen peas, thawed</li>
<li>2 cups cooked salmon in large chunks</li>
<li>2 green onions, thinly sliced, including the greens</li>
<li>Cilantro (or parsley) for garnish</li>
</ul>
</div>
答案 0 :(得分:4)
使用this
定位点击的li,li
将定位所有li
$(document).ready(function() {
$('#lili>li').click(function() {
$(this).css('background-color', 'yellow');
//-^-----
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>INGREDIENTS</h3>
<ul id="lili">
<li>3 Tbsp soy sauce</li>
<li>1 teaspoon brown sugar</li>
<li>1 Tbsp olive oil</li>
<li>2/3 cup diced red onion</li>
<li>2/3 cup diced red bell pepper</li>
<li>2 cloves garlic, minced</li>
<li>1-inch piece of ginger, grated</li>
<li>3 eggs, well beaten</li>
<li>4 cups day old cooked white rice (from about 2 cups of raw rice)</li>
<li>1 cup frozen peas, thawed</li>
<li>2 cups cooked salmon in large chunks</li>
<li>2 green onions, thinly sliced, including the greens</li>
<li>Cilantro (or parsley) for garnish</li>
</ul>
&#13;
如果您想切换效果,请使用以下内容
$(document).ready(function() {
$('#lili>li').click(function() {
$(this).toggleClass('toggle');
});
});
&#13;
.toggle {
background-color: yellow
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>INGREDIENTS</h3>
<ul id="lili">
<li>3 Tbsp soy sauce</li>
<li>1 teaspoon brown sugar</li>
<li>1 Tbsp olive oil</li>
<li>2/3 cup diced red onion</li>
<li>2/3 cup diced red bell pepper</li>
<li>2 cloves garlic, minced</li>
<li>1-inch piece of ginger, grated</li>
<li>3 eggs, well beaten</li>
<li>4 cups day old cooked white rice (from about 2 cups of raw rice)</li>
<li>1 cup frozen peas, thawed</li>
<li>2 cups cooked salmon in large chunks</li>
<li>2 green onions, thinly sliced, including the greens</li>
<li>Cilantro (or parsley) for garnish</li>
</ul>
&#13;
答案 1 :(得分:0)
您需要更改偶数源的css而不是所有li元素
$(this).css('background-color','yellow');
您也可以使用原生方法设置背景颜色,这将比前一个更快
this.style.backgroundColor = 'yellow';
答案 2 :(得分:0)
只需使用this
,因为这会引用当前点击的元素。
$(this).css('background-color','yellow');