2016-02-29 65 views
0

嗨我有一個html圖像按鈕與動態id範圍內golang模板。我需要爲它添加一個javascript函數。但問題是,我怎麼能在JavaScript中使用這個動態Id?如何使用javascript動態golang html模板ID?

我的HTML

的JavaScript

<script type="text/javascript"> 
     $().ready(function() { 
      $('#id{{.}}').click(function() { 
       $('#hidebody').toggle(); 

      }); 
     }); 
    </script> 

如何解決這個問題?有沒有更好的方法來做到這一點?

回答

2

給這些按鈕一個類。

{{range $i, $e := .Process}} 
    <input id="{{.}}" class="img-buttons" type="image" src="/images/icons/pencil.png" alt="edit" width="15" height="15"> 
{{end}} 

在javascript中,你可以做,

$(".img-buttons").click (function() { 
    $(this).attr("id"); // get Id 
}); 

相反,你可以使用HTML data attributes如果更適合你的id。

HTML:

{{range $i, $e := .Process}} 
    <input data-id="{{.}}" class="img-buttons" type="image" src="/images/icons/pencil.png" alt="edit" width="15" height="15"> 
{{end}} 

JS:

$(".img-buttons").click (function() { 
    $(this).data("id"); // get Id 
});