[英]Get hyperlink text when clicked on dynamically generated anchor tag
I am trying to display contents of sqllite table using bottle on html template file. 我正在尝试使用html模板文件上的瓶子显示sqllite表的内容。 And here is the handler code in the template file.
这是模板文件中的处理程序代码。
%for row in rows:
<tr>
%for col in row[0::2]:
<td><div class="box"><a class="button" href="#popup1" id ="a1">{{col}}</a></div></td>
%end
%end
It render the table as per the expectation on html page with three rows as data(please refer the below html source code which can be viewed on browser once the page is generated). 它根据html页面上的期望呈现表,并以三行作为数据(请参考下面的html源代码,生成页面后即可在浏览器上查看)。
<tr><td><div class="box"><a class="button" href="#popup1" id ="a1">Testbatch1</a></div></td></tr>
<tr><td><div class="box"><a class="button" href="#popup1" id ="a1">Testbatch2</a></div></td></tr>
<tr><td><div class="box"><a class="button" href="#popup1" id ="a1">Testbatch3</a></div></td></tr>
Now I have written simple javascript code to display text on the link ie. 现在,我已经编写了简单的JavaScript代码来在链接上显示文本,即。 value of {{col}} when it gets clicked
点击时{{col}}的值
<script language="javascript" type="text/javascript">
var batch = document.getElementById("a1").innerHTML;
window.alert(batch)
</script>
Now problem is, when I click on any of the hyperlink, JS display Testbatch1 in alert window. 现在的问题是,当我单击任何超链接时,JS在警报窗口中显示Testbatch1 。
I have also tried with below code, but still geting the same output 我也尝试过下面的代码,但仍然得到相同的输出
$('a1').click(function(){
window.alert($(this).text());
});
Can anyone suggest me how to get the hyperlink text of such dynamically generated anchor tags? 谁能建议我如何获取这种动态生成的锚标记的超链接文本? My aim is to read the text of the hyperlink when clicked and send back to my python code where I will use it as paramter for sql query to render some other output.
我的目的是在单击时阅读超链接的文本,并将其发送回我的python代码,在该代码中,我将使用它作为sql查询的参数来呈现其他输出。
As Identifiers must be unique. 由于标识符必须是唯一的。 You can't assign duplicate IDs.
您不能分配重复的ID。 CSS class can be used for binding event handler.
CSS类可用于绑定事件处理程序。 Here in snippet I have added
a1
class to anchor. 在此代码段中,我添加了
a1
类来定位。
%for row in rows:
<tr>
%for col in row[0::2]:
<td><div class="box"><a class="button a1" href="#popup1">{{col}}</a></div></td>
%end
%end
And for binding event handler use .on()
method with Event Delegation approach, when generating elements dynamically. 对于绑定事件处理程序,在动态生成元素时,请使用
.on()
方法和事件委托方法。
Example 例
$(document).on('click', ".a1", function(){
alert($(this).text())
});
In place of document
you should use closest static container. 代替
document
您应该使用最近的静态容器。
When you click on link .button class event is occurred 当您单击链接时,发生按钮类事件
$(document).on('click', ".button", function(){
alert($(this).text())
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.