简体   繁体   中英

Why does this simple code fail in firefox yet work in every other browser including opera and old IE versions

function T(x){ return (x.textContent) ? function(y){ x.textContent = y; } : function(y){ x.innerText = y; }; }

T(nodeA)('string');
nodeText = T(nodeB);
nodeText('string');

If I change (x.textContent) to (x.textContent !== undefined) it works in firefox. Otherwise I get no errors but nothing happens. Inspecting with firebug shows that T(node); returns function() , which is just baffling to me.

I'm new to javascript but I'm thinking this could be a bug?? I think it can only be true or false, it should be true and return first function but it doesn't return either. Can someone say why?

This won't work if the textContent for the given node is an empty string '' , which evaluates to false . That's why you should do (typeof x.textContent !== 'undefined') instead to ensure the existence of the property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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