Javascript FF和IE

时间:2013-04-11 19:05:00

标签: javascript html

我有以下脚本。它仅在Chrome中运行。我无法检查或激活该复选框。如何让它在FF和IE中运行?

<script type="text/javascript">
    function checkHoverButton() {
        var lis = document.getElementsByTagName('li');
        for( var i = 0, l = lis.length; i < l; i++ ) {
            lis[i].onclick = function() {

                var c = this.getElementsByTagName('input')[0];

                if ( c.checked ){
                    c.checked = 0;
                    this.style.background = 'white';    
                }
                else{
                    c.checked = 1;
                    this.style.background = '#eceff5';
                }
            };
        }
    }
</script>

<li class="friends-li">
  <span class="green">
     <input type="checkbox" value="<?php echo $value; ?>" id="form_friend_<?php echo $value; ?>" name="form[friend][]" />
  </span>
  <span class="pink">
    <img id="img_friend_<?php echo $value; ?>" src="">
  </span>
  <span class="blue">
    <label for="form_friend_<?php echo $value;?>" ><?php echo $label;?></label>
  </span>
</li>

2 个答案:

答案 0 :(得分:3)

首先,我假设您在代码中的某处调用了checkHoverButton

问题在于事件冒泡。

当您单击复选框或标签时,您基本上取消了该操作。您需要确保没有点击这些元素。

lis[i].onclick = function(e) {

    var clickedOn = (e.srcElement || e.target).nodeName;
    if(clickedOn==="INPUT"||clickedOn==="LABEL") return;     
    var c = this.getElementsByTagName('input')[0];

- 编辑 -

lis[i].onclick = function(e) {

    var clickedOn = (e.srcElement || e.target).nodeName;
    var setState = clickedOn!=="INPUT" && clickedOn!=="LABEL";     
    var c = this.getElementsByTagName('input')[0];
    if (setState) {
        c.checked = !c.checked;
    }
    this.style.background = c.checked ? "#eceff5" : "#fff";
};

答案 1 :(得分:1)

@epascarello方法非常好。

我做了一个例子,也许它有所帮助。

JSFiddle

var lis = document.getElementsByTagName('li'),
      checkHandler = function(event){
           event.stopPropagation();
      },
      clickHandler = function (event) {
            var c = this.getElementsByTagName('input')[0];
                  c.onclick = checkHandler;
            if (c.checked) {
                  c.checked = 0;
                  this.classList.remove('darker');
                  this.classList.add('white');
            } else {
                  c.checked = 1;
                  this.classList.remove('white');
                  this.classList.add('darker');
            }
            return false;
      };

for (var i = 0, l = lis.length; i < l; i++) {
      lis[i].onclick = clickHandler;
}