[英]Javascript works in a href but not in JS file
Hope everyone is fine. 希望大家一切都好。 Well I have a weird question, something that I'm missing or failing to understand. 好吧,我有一个奇怪的问题,这是我所缺少或无法理解的问题。 Hope anyone here can help me out. 希望这里有人能帮助我。 Well here goes, 好了,
Well I have an html page where I've defined a table with a few hard-coded values as below, 好吧,我有一个html页面,在其中定义了一个表,其中包含一些如下所示的硬编码值,
<table id='data-table' class='someClass'>
<thead>
<tr>
<th id="name-title">NAME</th>
</tr>
</thead>
<tbody>
<tr class="odd"><th class='c1'>Zachary Quinto</th></tr>
<tr class="even"><th class='c1'>Penny</th></tr>
<tr class="odd"><th class='c1'>Glen McGrath</th></tr>
</tbody>
</table>
Now I have a javascript file in which, somewhere down the code (Using jQuery), I do this, 现在,我有一个javascript文件,其中,在代码的某个位置(使用jQuery),我可以执行此操作,
$('#data-table').click(function() {
var value = $(this).find("th.c1").text();
if(value == "Zachary Quinto")
someFunc.showData('data-table', 1);
});
And for some reason this doesn't work, it goes over this function and I don't see any change/effect. 出于某种原因,它不起作用,它遍历了此功能,我看不到任何更改/效果。 However, to my amazement, If, when encapsulating my data into tags, it seem to work. 但是,令我惊讶的是,如果将数据封装到标签中,它似乎可以工作。 (By encapsulating, I mean something like below) (通过封装,我的意思是类似下面的内容)
<tr class="odd"><th class='c1'><a href="javascript:someFunc.showData('data-table', 1);">Zachary Quinto</a></th></tr>
<tr class="even"><th class='c1'><a href="javascript:someFunc.showData('data-table', 2);">Penny</a></th></tr>
<tr class="odd"><th class='c1'><a href="javascript:someFunc.showData('data-table', 3);">Glen McGrath</a></th></tr>
Can anyone please help me with this, I'm not really sure what I'm doing wrong in Javascript file which doesn't let me do this. 谁能帮我这个忙,我不太确定我在Javascript文件中做错了什么,而这不允许我这样做。 It's kind of weird as I thought both mean the same thing one way or another. 有点怪异,因为我认为两者在某种意义上都意味着同一件事。
Thanks a lot for your time. 非常感谢您的宝贵时间。
jQuery's text function returns the combined text of all matching elements. jQuery的text函数返回所有匹配元素的组合文本。 In your case, there are three th.c1
matches, so the text()
function returns Zachary QuintoPennyGlen McGrath
. 在您的情况下,有三个th.c1
匹配项,因此text()
函数返回Zachary QuintoPennyGlen McGrath
。
You can see this by throwing a breakpoint on your event handler in a debugger. 您可以通过在调试器中的事件处理程序上抛出断点来查看此情况。
Because something is wrong with your script. 因为您的脚本出了点问题。
You should write it as: 您应该将其编写为:
"use strict"; $('#data-table').on("click", "th", function(e) { e.preventDefault(); var value = $(this).text(); if(value == "Zachary Quinto") someFunc.showData('data-table', 1); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.