How to use dynamic golang html template id with javascript?

huangapple go评论82阅读模式
英文:

How to use dynamic golang html template id with javascript?

问题

你好,我可以帮你翻译。以下是翻译好的内容:

嗨,我有一个带有动态id的html图像按钮,它在golang模板中的范围内。我需要在其中添加一个javascript函数。但问题是,我如何在javascript中使用这个动态id?

我的HTML代码:

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

JavaScript代码:

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

如何解决这个问题?有没有更好的方法来做到这一点?

英文:

Hi I have a html image button with dynamic id inside range in golang template. I need to add a javascript function to it. But the problem is that how could I use this dynamic Id in javascript?

My HTML

{{range $i, $e := .Process}}
   &lt;input id=&quot;id{{.}}&quot; type=&quot;image&quot; src=&quot;/images/icons/pencil.png&quot; alt=&quot;edit&quot; width=&quot;15&quot; height=&quot;15&quot;&gt;
{{end}}

JavaScript

&lt;script type=&quot;text/javascript&quot;&gt;
	   $().ready(function() {
			$(&#39;#id{{.}}&#39;).click(function() {
				$(&#39;#hidebody&#39;).toggle();
		    	
			});
		});
	&lt;/script&gt;	

How to solve this? Is there any better way to do this?

答案1

得分: 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"); // 获取 Id
});

如果更适合你的话,你也可以使用 HTML 的 data 属性

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"); // 获取 Id
});
英文:

Give those buttons a class.

{{range $i, $e := .Process}}
   &lt;input id=&quot;{{.}}&quot; class=&quot;img-buttons&quot; type=&quot;image&quot; src=&quot;/images/icons/pencil.png&quot; alt=&quot;edit&quot; width=&quot;15&quot; height=&quot;15&quot;&gt;
{{end}}

In javascript you can do,

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

Instead of the id you can use html data attributes if that suits you better.

HTML:

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

JS:

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

huangapple
  • 本文由 发表于 2016年2月29日 15:34:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/35694126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定