2014-10-04 55 views
0

我想添加一個按鈕到某些文本字段以允許其他輸入方法。由於按鈕應該能夠引用它所屬的文本字段,因此我在該按鈕的onClick()處理函數中爲函數調用添加了一個參數,其中包含文本字段的ID。jQuery id不生成文本表示

至少,這是我的計劃。當我獲得文本字段的ID並將其顯示在警報中時,它會很好地顯示。但是,當我使用$(this).attr('id')的結果作爲函數參數時,我期望將一個字符串賦予該函數(元素的id)。而是給出一些奇怪的對象。

如何將該對象轉換爲字符串?或者有一個概念上的缺陷?

<form> 
<input class="joeDateTime" type="text" name="n1" id="n1" value="2014-09-01 17:30:00"> 
</form> 

<script> 
function handleJoeDateTime(e) 
{ 
    alert('Edit '+e); // shows 'Edit [object HTMLInputElement]' 
} 

$(document).ready(function() { 

    $('.joeDateTime').each(function(){ 
     var i = $(this).attr('id'); 
     alert(i); // shows 'n1' 
     $('<button onclick="handleJoeDateTime(' + i + ');return false;"></button>').insertAfter($(this)); 
    }); 

}); 
</script> 

回答

1

你的問題就在這裏:

$('<button onclick="handleJoeDateTime(' + i + ');return false;"></button>') 

哪裏,這應該是

$('<button onclick=\"handleJoeDateTime(\"' + i + '\");return false;\"></button>') 

當你傳遞給jQuery的($)的元素,它成爲一個jQuery對象。 它已經被用來處理id,class,元素,而不是html塊。 你想要的是插入一個連接元素作爲一個html節點。

所以首先連接你的元素,然後附加jQuery的after()方法。
(或創建/與vanilia JS var btn = document.createElement("BUTTON");其追加)

var Button = '<button class=\"AltBut\" id=\"' + i + '\"></button>'; 
$(this).after(Button); 

或(對於密實)

$(this).after('<button class=\"AltBut\" id=\"' + i + '\"></button>'); 

在本例,我加入一個id每個已啓用按鈕在哪裏存儲您的變量i

然後爲這些按鈕添加一個點擊監聽器,避免所有價格的內聯js,以維護可用性。

$('.AltBut').on('click',function(){ 
     var i = $(this).attr("id"); 
     alert("i= "+i); 
     return false; 
}) 

整個演示是在這裏:http://jsfiddle.net/x6x4v90y/1/

+0

感謝您指出我的缺點,更在適當的風格的洞察力。 :-) – 2014-10-04 08:44:18

2

你是不是傳遞i作爲一個字符串值,你是把它當作一個變量。在現代瀏覽器中,元素的ID被複制到窗口對象的屬性中(因此可以作爲全局變量訪問)。

因此,你需要用引號括他們通過i作爲一個字符串值

$('<button onclick="handleJoeDateTime(\'' + i + '\');return false;"></button>').insertAfter($(this)); 

演示:Fiddle


而且除了使用內聯事件處理程序的,我會建議使用jQuery事件handlres

$('.joeDateTime').each(function() { 
    var i = $(this).attr('id'); 
    console.log(i); // shows 'n1' 
    $('<button />', { 
     text: '', 
     click: function() { 
      handleJoeDateTime(i); 
      return false; 
     } 
    }).insertAfter(this); 
}); 

演示:Fiddle