2015-07-13 60 views
-1

我有這個成功的AJAX功能:JQuery/HTML:如何爲元素的多個ID提供.click函數?

success: function (data){ 

     var str = JSON.stringify(data); 
     var obj = JSON.parse(str); 
    for(var i= 1; i<=obj.length-1;i++) 
     { 
      $('#Name').append(obj[i].Name + "<br>"); 
      $(this).attr('id',obj[i].Id); 
      $('#this.id').click(function(){ 
      window.location.href = "test.html"; 
      }) 
     } 

HTML代碼:

<table class="table table-striped table-bordered table-hover " id= "TableData" border : "1 px solid black"> 
<tr> 
    <td>Product Name </td> 
    <td id="Name"> </td> 
</tr> 
</table> 

我想提供一個鏈接名稱的每一個ID。
例如:輸出是這樣的:

ABC0
ABC1
ABC2
ABC3

我想每一個ABC鏈接到另一個網頁使用。點擊的jQuery()屬性。 我該如何做到這一點?給定的代碼不起作用。 請幫助。

+0

您'$的意思( '#this.id')' – Sadikhasan

+0

我的意思是該名稱的ID。這是我困惑的地區。因此,這個問題。我正在嘗試爲每個ABC提供唯一的ID(請參閱輸出)。 –

+0

你想實現什麼? – Sadikhasan

回答

-1

$(this)的結果是什麼?那指向哪裏?你有沒有試過用console.log檢查它? 此外,$(「#this.id」)肯定是錯誤的,你正在尋找id =「this」和class =「id」的元素,可能不存在。你應該用(「#」+ obj [i] .Id)替換它。 除此之外,我不太清楚$(this)對你有什麼作用。你在id =「Name」中添加純文本,但是你如何爲它們設置一個id?你有沒有嘗試做一個附件,至此已經聲明Name和Id?類似於

$('#Name').append('<span id="' + obj[i].Id + '">' + obj[i].Name + '</span><br>'); 
$('#' + obj[i].Id).click(function(){window.location.href = "test.html";}) 
+0

'#this.id'將選擇' – Justinas

+0

是的,對不起@Justinas –

0

您可以使用startsWith屬性選擇器。這是委託給document水平,從而無需設置它在任何類型的循環:

$(document).on('click', '[id^=ABC]', function(){ 
    // do stuff with 'this.id' 
}); 
+0

請檢查這個''[id^= ABC]'' –

+0

@JohnR我需要檢查什麼? –

+0

它必須像這樣只有''[id^=「ABC」]''對嗎?我是對還是錯? –

0

我可以看到你的代碼的幾個問題,你不能在同一頁上ID的多個實例。我寧願使用這個類。另外我假設 我不明白你的問題100%,但我認爲你正試圖在所有td上添加一個點擊事件。與此不同,向所有relaveant td添加一個名爲data-link的數據屬性,並在主表上添加一個單擊元素,以便在單擊該表時觸發該事件。然後使用event.target來查找被點擊的元素,並檢查它是否具有相關的數據屬性,如果它具有attr數據鏈接,則可以提取該值並重定向它。

$(document).ready(function() { 
    $("#mainTable").click(function(event){ 
     if(event.target.hasAttribute("data-link")){ 
     //this is where you would have your code 
     console.log(event.target.getAttribute('data-link')); 
     } 
    }); 
    }); 
0

*您可以指定一個公共類的各個環節,並簡單地添加點擊事件爲類,如:

success: function (data){ 
     var str = JSON.stringify(data); 
     var obj = JSON.parse(str); 
    for(var i= 1; i<=obj.length-1;i++) 
     { 
      var node= $('<a class="linknav">'+obj[i].Name+'</a><br>') 
      node.attr('id',obj[i].Id); 
      $('#Name').append(node); 
     } 
} 

$(document).on('click','.linknav',function(){ 
window.location.href = "test.html"; 
}); 
0

試試這個訪問的所有元素的ID開始與ABC

代碼片段:

$("[id^='ABC']").click(function(){ 
     window.location.href = "test.html"; 
    }); 

,這也

success: function (data){ 

    var str = JSON.stringify(data); 
    var obj = JSON.parse(str); 
    for(var i= 1; i<=obj.length-1;i++) 
    { 
     $('#Name').append(obj[i].Name + "<br>"); 
     $(this).attr('id',obj[i].Id);   
    } 
    //... 
相關問題