2017-01-06 38 views
0

我有一個循環,其中我輸出按鈕作爲數組valstime的長度。獲取點擊循環的按鈕的ID

var html =''; 
    for (var j=0, n=valstime.length; j<n; j++) 
     { 
     html += ' <tr>'; 
     html += ' <td>'+'<button class="btn btn-default" value="'+(valstime[j])+'" id="time<?php echo $post->ID?>'+j+'">'+(valstime[j])+'</button>'+'</td>'; 
     html +=  '</tr>'; 
     } 
    $("#times<?php echo $post->ID?>").append(html); 

現在我想要點擊的按鈕的HTML。首先我用

id="time<?php echo $post->ID?>" 

,當我得到按鈕的HTML我只得到第一個因爲ID不能是相同的,如果是同一個jQuery將僅得到第一個。所以我做了這個。

id="time<?php echo $post->ID?>'+j+'" 

現在,每個按鈕的id都不相同。我正在使用此代碼獲取由其id標識點擊的html。

$("#time<?php echo $post->ID?>").click(function(){ 
    var ttime = $(this).html(); 
    console.log(ttime); 
    var timestr=ttime; 
    var time=new Date();   
    time.setHours(parseInt(timestr.split(":")[0])+1,00,00); 
    var newtime= formatAMPM(time); 
    $(".tt_time").val(ttime+' - '+newtime); 
    $(".tt_time").html(ttime+' - '+newtime); 

}); 

現在我想獲得點擊哪個按鈕的id的id並通過id來獲取它的html。

$("#clicked ID here").click(function(){ 

我也試過這個,但沒有。我知道這不是一個好方法。

for (var k=0; k<10; k++) 
        { 
$("#time<?php echo $post->ID?>'+k+'").click(function(){ 

任何人都可以提出一些建議嗎?

+0

將類添加到該按鈕並在類上觸發事件,在單擊事件中,您將獲得單擊的元素詳細信息。 – prathmeshb1

回答

2

使用$(this)獲得按鈕的背景點擊:

綁定click事件上class通用於所有buttons像下面

$(document).on("click", ".btn", function(){ 
    console.log($(this).attr("id")); 
}); 

$(function() { 
 
    $(document).on("click", ".btn", function() { 
 
    alert($(this).attr("id")) 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="btn" id="btn1">Button 1</button> 
 
<button class="btn" id="btn2">Button 2</button> 
 
<button class="btn" id="btn3">Button 3</button>

+0

謝謝 我得到了編號 我可以這樣做嗎? var ttime = $(id).html(); 它不工作。得到這個錯誤 無法讀取未定義的屬性「拆分」 –

+0

我想獲得該按鈕被點擊的HTML。因爲我在id變量中獲取它的id。我怎樣才能通過它來獲取HTML? –

+1

它的完成謝謝你 –

0

可以綁定onclick事件,而你正在創建它的HTML d ynamically。

html += '<td>'+'<button class="btn btn-default" value="'+(valstime[j])+'" 
      onclick="GetPostID(time<?php echo $post->ID?>)" 
      id="time<?php echo $post->ID?>'+j+'">' 
      +(valstime[j])+'</button>'+'</td>'; 

現在的jQuery

function GetPostID(id) { 
//here is your id 
} 
0

添加 「GET_TIME」 在TD

var html =''; 
    for (var j=0, n=valstime.length; j<n; j++) 
     { 
     html += ' <tr>'; 
     html += ' <td>'+'<button class="btn btn-default get_time" value="'+(valstime[j])+'" id="time<?php echo $post->ID?>'+j+'">'+(valstime[j])+'</button>'+'</td>'; 
     html +=  '</tr>'; 
     } 
    $("#times<?php echo $post->ID?>").append(html); 


$(document).on('click','.get_time',function(){ 
    // you will get everything here 
    console.log($(this).attr("id")); 
    console.log($(this).text(); 
    console.log($(this).html(); 
}); 

類希望它爲你工作。