Django生成<td>点击后JavaScript获取值为空,如何解决?
问题解决思路
你的代码有两个关键问题导致获取不到hostname:
1. this指向错误
直接写onclick="clientInfo()"时,函数内部的this指向的是全局window对象,不是触发点击的<a>元素,所以$(this).closest("tr")没法定位到正确的表格行。
2. 选择器写错
$row.find("hostname")是在查找名为<hostname>的标签,但你的目标是class为hostname的<td>,必须用类选择器.hostname。
修正方案(两种可选)
方案一:传递this给函数
修改HTML的onclick调用,把当前元素传进去:
<td class="hostname"><a href="javascript:void(0)" onclick="clientInfo(this);">Client001</a></td>
然后修改JS函数,接收传入的元素:
function clientInfo(el) { var $row = $(el).closest("tr"); var hostname = $row.find(".hostname").text(); alert(hostname); }
方案二:用事件委托(更推荐)
移除内联onclick事件,给<a>加个类名,然后用jQuery事件委托绑定点击:
<td class="hostname"><a href="javascript:void(0)" class="client-link">Client001</a></td>
JS代码:
$(document).on("click", ".client-link", function() { var $row = $(this).closest("tr"); var hostname = $row.find(".hostname").text(); alert(hostname); });
额外优化:让整个<td>可点击
如果你的需求是让整个<td>都能点击,没必要套<a>标签,直接给<td>绑定事件更简单:
<td class="hostname client-cell">Client001</td>
JS代码:
$(document).on("click", ".client-cell", function() { var hostname = $(this).text(); alert(hostname); });
内容的提问来源于stack exchange,提问作者jonat-han
相关产品推荐
相关产品推荐

