简体   繁体   中英

javascript disabled button ondblclick with this

I have a button that has a doubleclick event, that I want to run, regardless of whether the button is enabled or disabled. I posted a similar question about this here , but now I need to run a function from the disabled button that uses the this paramater, and if I use the <span> workaround, as described in the other question, it gives me the info about the <span> element, not the <button> element.

jsfiddle example

How can I get round this?

First of all, you can't have two elements with same ids. Your markup should look like that:

<button name='name_of_button' id='id_of_button1' ondblclick="runFunction( this );">Enabled Button</button>
<br>
<button name='name_of_button' id='id_of_button2' ondblclick="runFunction( this );" disabled>Disabled Button</button>

Second, it is not a good idea to use inline javascript. However, your problem could be solved like that:

HTML:

<div class="wrapper">
    <button name='name_of_button'>Enabled Button</button>
    <div class="over"></div>
</div>
<div class="wrapper">
    <button name='name_of_button' disabled="disabled">Disabled Button</button>
    <div class="over"></div>
</div>

JS:

window.onload = function() {
    var dblClicked = function() {
        console.log(this.parentNode.childNodes[1].removeAttribute("disabled"));
    }
    var overlays = document.querySelectorAll(".wrapper .over");
    for(var i=0; i<overlays.length; i++) {
        var over = overlays[i];        
        over.addEventListener("dblclick", dblClicked);
    }
}

http://jsfiddle.net/NRKLG/12/

If the element is disabled it can't trigger events. This means that you can't listen for dblclick even if you add the listener to the parent element. So, you should put an overlay transparent div over the button.

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