使用onClick动态构建按钮



我正在用JavaScript动态构建一个按钮,这将包括一个onClick事件。onClick事件需要聚焦存储在变量中的字段。

我找不到使用字段变量本身的方法,所以决定尝试使用JQuery对象中的field.selector属性,该属性将包含"。

以下是当前结构的代码片段。

InvalidField.prototype.getMessageStructure = function(){
    var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
        <button class="inputButton" 
            Value="Go To Field" 
            onclick='goToFieldFromAlert($('' + this._field.selector + ''))'
        />
    </div>';
    return structure;
};

这正在输出:

<button class="inputButton" 
    value="Go To Field" 
    onclick="goToFieldFromAlert($(" input[name="applicant.email" ]'))'="">
</button>

正如你所看到的,报价不会被正确地输出,所以点击就会中断。

有人能预见到一种更好的方式来履行这一职能或纠正报价吗?我从这个SO Answer中看到DOM不尊重引号,这就是目前导致我出现问题的原因。

谨致问候。

正如我在评论中提到的,完全避免使用onclick。jQuery事件处理程序要灵活得多(并且支持多个事件处理程序)。

1) 将字段名(仅限于jQuery选择器,而非jQuery选择器)注入数据属性:

InvalidField.prototype.getMessageStructure = function(){
    var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
        <button class="inputButton" 
            value="Go To Field" data-field="' + this._field.name + '"/>
    </div>';
    return structure;
};

2) 使用委托的事件处理程序可以以较少的开销获得inputButtons上的所有单击。提取字段名称并在其所属位置执行jQuery:

  $(document).on('click', '.inputButton', function() {
       var $button = $(this);
       var field = $button.data('field');
       goToFieldFromAlert('input[name="' + field + '"]');
  });

您应该使用jQuery创建元素。这是一种更干净、无错误的方法

代码示例

InvalidField.prototype.getMessageStructure = function(){
    var structure = 
        $('<div></div>').append(
            $('<span></span>').text(this._message)
        );
    structure.append(
        $('<button></button>')
            .addClass('inputButton')
            .text("Go To Field")
            .click(function(){
                goToFieldFromAlert($(this._field.selector));
            })
    );          
    return structure;
};

以下示例将动态添加按钮:

hello.forEach( function(result) {
  var card = document.createElement("input");
  card.type = "button";
  card.onclick = function() {
     newcard( result );
  }
  card.value = value; // some value
  card.style.backgroundColor="#5ABC7B";
  document.body.appendChild(card);
});

最新更新