开发者

Issue with .checked

开发者 https://www.devze.com 2023-04-12 00:43 出处:网络
I am helping someone fix their plain javascript highlight-when-c开发者_运维技巧hecked DEMO If you click yes or no, you will see it breaks and makes an unchecked row highlighted.

I am helping someone fix their plain javascript highlight-when-c开发者_运维技巧hecked

DEMO

If you click yes or no, you will see it breaks and makes an unchecked row highlighted.

I know I could rewrite it in jQuery, but I would REALLY like to know what makes it fail

Thanks


It's because you're adding the classname every time. So if you change between yes/no 5 times, item3 will have classname radio-item myclass myclass myclass myclass myclass. So in your replace you need to make sure it's global (replacing every occurance of the search string)

edit:

This code is adding the classname without checking if it's there in the first place. Remember, you're looping all checkboxes, for every change on any of them.

if (inputArray[i].checked) {
    inputArray[i].parentNode.className += " myclass";
}    


Here's some library functions I wrote some time ago:

function trim(s) {
  return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}

function hasClassName(el, cName) {
    if (typeof el == 'string') el = document.getElementById(el);

    var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
    return el && re.test(el.className);
}

function addClassName(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (!hasClassName(el, cName)) {
        el.className = trim(el.className + ' ' + cName);
    }
}

function removeClassName(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (hasClassName(el, cName)) {
        var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
        el.className = trim(el.className.replace(re, ''));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号