Javascript Bug: set audio object controls attribute True = = False

I'm rather new to this and don't know exactly how to report a bug, but I first want to confirm it's a bug and then go on from there. But here's what I'm finding:

1) When creating an audio object controls attribute, the controls attribute will respond to a string as if it's a boolean. For Instance:

<button onclick="example()">Try this</button>
<script>

function example() {
    var aud = document.createElement("AUDIO");
        aud.setAttribute("src","example.mp3");
    aud.setAttribute("controls", "controls");
}

Okay, we've put controls in there because it makes controls equal controls: Thing is, you can put any old string in there and it works just fine -- apple, banana, pear, anything.

2) Isn't the value suppose to be a boolean? Well when you try a boolean, false for example, you still get true. (False == True) It works just as if you typed in true.

...and if you put anything else other than true or false (just type anything other than an integer, string, or true or false value), you get false (or it just doesn't work). Everything equals true and a non-string, non-integer equals false (or just doesn't work).

Finally, you can even try setting the controls attribute on an accessed audio element:

var aud = document.getElementById("idhere");
function accessAudioElement() { 
    aud.controls = false;
} 

At least here the true and false actually work as true and false, but once again, any string or integer will also get you true and any non-string/non-integer will break the code.

Can somebody help me out here because I don't think this is suppose to work this way... and if does, what's the point of using a boolean value when most anything else will work?

Of course I'm still learning, so maybe this is not a bug, maybe for some reason this is suppose to work this way, but if that's the case would someone please share the logic behind this with me.

I'm just not understanding. Thanks Magic


You might want to read/search more about Javascript Truthy $ Falsey. It is very important.

https://j11y.io/javascript/truthy-falsey/

在这里输入图像描述


This is an extended answer of what @nnnnnn suggested in the comments.

aud.controls = false; doesn't set the attribute, it sets the property.

You need to use setAttribute() method to add the specified attribute to an element.

aud.setAttribute("controls", "controls");

And use removeAttribute() method removes the specified attribute from an element.

aud.removeAttribute("controls");

For more reading on these methods, have a look at the hyperlinks attached.

  • Element.setAttribute()
  • Element.removeAttribute()
  • When to use setAttribute vs .attribute= in JavaScript?
  • HTML - attributes vs properties
  • 链接地址: http://www.djcxy.com/p/13026.html

    上一篇: 检查数组中是否存在元素

    下一篇: Javascript错误:设置音频对象控件属性True = = False