【问题标题】:Onclick eventhandler giving out a value [JS]Onclick 事件处理程序给出一个值 [JS]
【发布时间】:2019-02-17 01:49:18
【问题描述】:

有什么样的可能性让 onclick 事件处理程序给出一个值(真,假),所以它可以被另一个函数用来做出逻辑决策(如果单击按钮这样做,如果不这样做).. .

我的代码:

function toggleBoolean(){
document.getElementById("click").onclick=function(){
return true;}
}

【问题讨论】:

    标签: javascript dynamic onclick boolean eventhandler


    【解决方案1】:

    我为你创建了一个小例子,(我希望)能满足你的需求。

    /**
     * Performs an operation based on the provided parameter.
     */
    function toggleBoolean(checked) {
      // Find the div element in the DOM and exit if it can't be found.
      const
        statusIndicator = document.getElementById('theBoolean');
      if (statusIndicator === null) {
        return;
      }
      
      // When the checked parameter is true, add the is-active CSS class
      // to the div element; otherwise remove the class.
      if (checked){
        statusIndicator.classList.add('is-active');
      } else {
        statusIndicator.classList.remove('is-active');
      }
    }
    
    /**
     * This method handles the event dispatched when the button to
     * toggle the boolean is clicked.
     */
    function onButtonClicked(event) {
      // Call the method, pass the value true along to the method.
      toggleBoolean(true);
    }
    
    // Get the element from the DOM.
    const
      button = document.getElementById('myButton');
    // Make sure the element exists before assigning something
    // to it or your code will crash.
    if (button !== null) {
      // Add an event listener for the click event.
      button.addEventListener('click', onButtonClicked);
    }
    
    // Set the boolean value to false.
    toggleBoolean(false);
    .status-indicator {
      background-color: red;
      height: 40px;
      margin-top: 10px;
      width: 40px;
    }
    
    .status-indicator.is-active {
      background-color: blue;
    }
    <button id="myButton" type="button">Click me</button>
    
    <div id="theBoolean" class="status-indicator"></div>

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多