【问题标题】:Create element from HTML but pass a function as a handle从 HTML 创建元素,但将函数作为句柄传递
【发布时间】:2017-05-08 22:11:36
【问题描述】:
function createResendIVButton(userId, name){
    return '<span class=btn onclick=usersTable.resendInvestorVerification("'+userId+'","'+name+'")>resend&nbsp;I.V.</span>';
}

当创建一个 HTML 元素时,是否有可能以某种方式发送函数句柄而不是字符串(函数名)?由于可见性问题,字符串不方便。而且我需要从 HTML 创建,因为我使用的库不允许我轻松访问其 DOM,但允许我从 HTML 代码初始化行。

【问题讨论】:

标签: javascript dom


【解决方案1】:

创建一个 DOM 元素并绑定一个动作:

        function createResendIVButton(userId, name){

            var button = document.createElement('span');
            button.className = 'btn';

            button.addEventListener('click', function(){

                console.log(userId);
                console.log(name);

            });

            button.innerHTML = 'click on me';

            return button;

        }

【讨论】:

    【解决方案2】:

    像这样?

    function createResendIVButton(userId, name) {
      var span = document.createElement('span');
      span.innerHTML = 'resend I.V';
      span.onclick = function() {
        usersTable.resendInvestorVerfication(userId, name);
      }
      
      var div = document.getElementById('somecontent');
      div.appendChild(span);
    }
    
    
    createResendIVButton(1, 'Joe');
    #somecontent {
      width: 100px;
      height: 100px;
      background: #ccc;
     }
    <div id='somecontent'>
    </div>

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多