2014-09-04 227 views
0

我在JavaScript中動態構建了一個按鈕,這將包含一個onClick事件。 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不尊重當前導致我問題的引用。

親切的問候。

+1

只需轉義引號? – Nit 2014-09-04 09:46:11

+2

在jQuery中,作爲一般準則,將事件處理程序附加到元素。不要使用'onclick'屬性。對於屬性'onclick =「...」''無論如何,雙引號也是標準的:) – 2014-09-04 09:49:21

+0

@TrueBlueAussie在onclick事件中使用雙引號作爲標準的問題在於jquery.selector在其中引用了引號,除非我使用.replace,否則它就會逃跑,然後開始變得更加混亂。 – 2014-09-04 10:13:54

回答

1

正如我在評論中提到,應避免使用onclick在所有。 jQuery事件處理程序更加靈活(並支持多個事件處理程序)。

1)注入的字段名(只,而不是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 + '"]'); 
    }); 
+0

哦,有趣的是,我不知道我可以將信息附加到按鈕本身。這是禁止單獨點擊事件的因素。學到了非常有用的東西! – 2014-09-04 13:15:54

+1

@David Moores:'data-'屬性與jQuery插件緊密相關,並且比通常的* options *對象更加靈活,因此我強烈建議使用'data-'屬性來獲取額外的數據到頁面爲jQuery。 – 2014-09-04 13:17:05

1

您應該使用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; 
}; 
+0

有趣的是,我不熟悉選擇器之外的JQuery,所以我會閱讀這種方法。代碼不適合我,但我覺得這是由於我提供的摘錄以外的事情。 – 2014-09-04 10:36:26

+1

謝謝Satpal,我最終使用了你和TrueBlue的反應。現在感覺更清潔了。 – 2014-09-04 13:27:29

0

下面的例子將動態地添加按鈕的一個例子:

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); 
});