简体   繁体   English

javascript禁用按钮ondblclick与此

[英]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. 我有一个要运行的doubleclick事件按钮,无论该按钮是启用还是禁用。 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. 我在这里发布了与此类似的问题,但是现在我需要从使用this参数的禁用按钮运行一个函数,并且如果我使用<span>解决方法(如另一个问题中所述),它将为我提供有关<span>元素,而不是<button>元素。

jsfiddle example jsfiddle示例

How can I get round this? 我该如何解决?

First of all, you can't have two elements with same ids. 首先,不能有两个具有相同ID的元素。 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. 其次,使用内联JavaScript不是一个好主意。 However, your problem could be solved like that: 但是,您的问题可以这样解决:

HTML: 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: 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/ 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. 这意味着即使将侦听器添加到父元素,也无法侦听dblclick。 So, you should put an overlay transparent div over the button. 因此,您应该在按钮上放置一个覆盖透明的div。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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