Javascript在href中工作,但在JS文件中不起作用

Javascript works in a href but not in JS file

本文关键字:JS 文件 不起作用 但在 工作 href Javascript      更新时间:2023-09-26

希望大家都没事。好吧,我有一个奇怪的问题,我错过或无法理解的东西。希望这里的任何人都可以帮助我。好吧,在这里,

好吧,我

有一个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>

现在我有一个javascript文件,在代码的某个地方(使用jQuery),我这样做,

$('#data-table').click(function() {
    var value = $(this).find("th.c1").text();
    if(value == "Zachary Quinto")
        someFunc.showData('data-table', 1);        
});

由于某种原因,这不起作用,它超过了这个函数,我没有看到任何变化/效果。然而,令我惊讶的是,如果在将我的数据封装到标签中时,它似乎有效。(通过封装,我的意思是下面这样的东西)

<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>

任何人都可以帮我解决这个问题,我真的不确定我在 Javascript 文件中做错了什么,这不允许我这样做。这有点奇怪,因为我认为两者以一种或另一种方式意味着同样的事情。

非常感谢您的时间。

因为你的脚本有问题.
你应该把它写成:

"使用严格";$('#data-table').on("click", "th", function(e) {    e.preventDefault();    var value = $(this).text();    if(value == "Zachary Quinto")        someFunc.showData('data-table', 1);       });

jQuery的text函数返回所有匹配元素的组合文本。在您的情况下,有三个th.c1匹配项,因此 text() 函数返回 Zachary QuintoPennyGlen McGrath

可以通过在调试器中的事件处理程序上引发断点来查看这一点。