简体   繁体   English

更改点击元素的样式

[英]Changing clicking element's style

Here is very newbie problem. 这是一个非常新手的问题。
There is three options like checkbox in demo . 有3个选项,例如demo中的复选框。 When the option is clicked, i want to change background color of clicked option like checkbox. 当单击选项时,我想更改单击选项的背景颜色,如复选框。
I couldn't figure out the problem due to the id of the options are same which is option . 我无法弄清楚这个问题,由于选项的ID是相同的是option

A possible implementation in query could be: 查询中可能的实现可能是:

$(document).ready(function(){
    $(".myCheckboxClass").bind('click', function(){
        $(this).css('background-color', 'red');
    });

});

You can basically do the same in js, just check the proper syntax. 您基本上可以在js中执行相同的操作,只需检查正确的语法即可。 The key thing is the "this" selection of the clicked element. 关键是单击元素的“ this”选择。

use class instead of id , since (as its name already says) id must be unique, otherwise it is not an id anymore.. 使用class而不是id ,因为(正如其名称已经说明的那样) id必须是唯一的,否则它不再是id。

repaired and working version: http://jsfiddle.net/hvWeG/5/ 修复且可以运行的版本: http : //jsfiddle.net/hvWeG/5/

$(function(){
  $('.option').on('click',function(){
   $(this).css('background-color','yellow');
  });
});

html HTML

<ul style="display:block;" id="options">
    <li class="option">Cucumber</li>
    <li class="option">Tomato</li>
    <li class="option">Potato</li>
</ul>

Check this out check edited Code here 这里检查编辑代码

1> First of all your fucntion should be in head,in jsfiddle near the left top corner change the onload to no wrap in head , 1>首先,您的功能应该在头部,在左上角附近的jsfiddle中,将onload更改为no wrap in head

2> you dont need script tag in onclick 2>您不需要onclick中的脚本标签

3> document.getElementById('option') will select only the first element with id 'option' Check the following code , i have made some minor changes to your code. 3> document.getElementById('option')将仅选择id为'option'的第一个元素。检查以下代码,我对您的代码做了一些小的更改。 check edited Code here 在此处检查已编辑的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM