使复选框可检查

时间:2014-11-18 22:20:31

标签: javascript jquery

我有隐藏的复选框,我无法访问JS代码,这使我可以执行复选框检查。我该怎么办?

我从stackoverflow尝试了一些JS,但它没有用。

这是我的代码http://fiddle.jshell.net/ta7w7bb8/

CSS:

    .obalform label.checkbox{
    font-size:18px;
    color:#2d2f36;
    width:478px;
    margin:auto;
    text-align: left;
    display:inline-block;
    float:none;
    cursor:pointer;
}

.checkbox::before{
    content:"";
    width:25px;
    height:25px;
    background:url(http://i.imgbox.com/dMtoesFn.png) 0 0 no-repeat;
    float:left;
    cursor:pointer;
    margin-top: 14px;
    margin-right: 15px;
}



.checkbox.checked::before{
    content:"";
    width:25px;
    height:25px;
    background:url(http://i.imgbox.com/fpOcnxmf.png) 0 0 no-repeat;
    float:left;
    cursor:pointer;
    margin-top: 14px;
    margin-right: 15px;
}

.checkbox:hover::before{
    content:"";
    width:25px;
    height:25px;
    background:url(http://i.imgbox.com/fpOcnxmf.png) 0 0 no-repeat;
    float:left;
    cursor:pointer;
    margin-top: 14px;
    margin-right: 15px;
}

input[type=checkbox]{display:none;}

HTML:

<div class="obalform">
          <div class="radek">
              <label class="checkbox" for="check1">souhlas se zasíláním slevových kupónů,akcí a novinek</label><input id="check1" type="checkbox" name="souhlas">
          </div> 
      </div>

我尝试了这个主题的解决方案 - &gt; HTML checkbox onclick called in Javascript

3 个答案:

答案 0 :(得分:2)

您必须使用CSS3:checked选择器,但您必须在更改之前更改HTML结构...我已经为您编写了一个示例:

http://fiddle.jshell.net/Clear/ta7w7bb8/4/(使用此代码,您不需要javascript)


知道在我的样本中我使用了名为“Font Awesome”的标志性字体。这是更好的,因为使用此字体您不应使用图像,页面加载较少

答案 1 :(得分:1)

如果你想在jQuery中做同样的事情,你可以这样做:

function getLabel(needle) {
    var labels = document.getElementsByTagName("label");
    var texts = [] ;
    for (var i = 0; i < labels.length; i++) {
        var label = labels[i];
        if(label.getAttribute("for") == needle) {
            return label;
        } 
    }
    return null;
 }

function checked() {
    var label = getLabel('check1');
    var selection = this.checked ? "checkbox checked": "checkbox";

    if ( selection ) label.setAttribute('class', selection); 
    else label.removeAttribute('class');
}

// add event listener to checkbox
var el = document.getElementById("check1");
el.addEventListener("click", checked, false);

它的代码比jQuery多,但它更轻,加载速度更快。这取决于你将要做什么。

你可以找到小提琴here.

答案 2 :(得分:0)

您的代码是人工插入代表复选框状态的图像。当&#34;检查&#34;时,图像看起来被检查class适用于<label>。您需要重新组织CSS / HTML,或者您可以编写一些JavaScript来添加或删除&#34;已检查&#34;当复选框更新时,为<label>的课程。

以下是一个简单的jQuery脚本,可以解决问题&#34;已检查&#34;类。

$(function() {
    $("input[type='checkbox']").on('change', function() {
        var $this = $(this);
        var checked = $this.is(":checked");
        if (checked)
            $this.closest(".radek").find("label").addClass("checked");
        else 
            $this.closest(".radek").find("label").removeClass("checked");
    });
});

Updated Fiddle

相关问题