<a> tag click event won&#39;t work

时间:2017-02-01 18:39:47

标签: javascript jquery html

I have the following html(+razor) :

<div id = "years" class="btn-group btn-group-justified timeline">
    <a  href="#@DateTime.Now.Year" class="btn btn-primary">@DateTime.Now.Year</a>
    <a  href="#@DateTime.Now.AddYears(-1).Year" class="btn btn-primary">@DateTime.Now.AddYears(-1).Year</a>
    <a  href="#@DateTime.Now.AddYears(-2).Year" class="btn btn-primary">@DateTime.Now.AddYears(-2).Year</a>
</div>

I simply want to have use these as buttons and something to happen on click. Therefore I have the following jquery, which won't work :

$(".btn a").click(function () {
        console.log('click');

            var txt = $(this).text();
            console.log(txt);
            alert(txt);


    });

I simply want to have the value inbetween the on click. Right now, when I click one of the buttons, nothing happens. Neither I get 'click' written on the console, nor i get an alert with the text in the tag. Can someone help make this work?

3 个答案:

答案 0 :(得分:2)

iterm2 build 3.0.13正在寻找SELECT TOP (1) * From [dbo].[Y] WITH (NOLOCK); 级后代的$(".btn a")代码。那不是你拥有的

只需使用内部侦听器并摆脱外部侦听器。在其他事件处理程序中创建事件侦听器不是一个好习惯,除非你真的有充分的理由知道你在做什么

&#13;
&#13;
<a>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你的封闭div没有.btn类,所以你的jquery选择器找不到任何东西。尝试:

$(".btn-group a").click(...)

答案 2 :(得分:1)

您可以尝试使用此代码

示例#1:

&#13;
&#13;
tail -n500 /var/log/messages
&#13;
&#13;
&#13; 示例#2:

&#13;
&#13;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id = "years" class="btn-group btn-group-justified timeline">
    <a  href="#@DateTime.Now.Year" class="btn btn-primary">@DateTime.Now.Year</a><br><br>
    <a  href="#@DateTime.Now.AddYears(-1).Year" class="btn btn-primary">@DateTime.Now.AddYears(-1).Year</a><br><br>
    <a  href="#@DateTime.Now.AddYears(-2).Year" class="btn btn-primary">@DateTime.Now.AddYears(-2).Year</a>
</div>
<script>
$("a.btn").click(function(e){
e.preventDefault();
 console.log(this);
alert("click");
});
</script>
</body>
</html>
&#13;
&#13;
&#13;

示例#3:

&#13;
&#13;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id = "years" class="btn-group btn-group-justified timeline">
    <a  href="#@DateTime.Now.Year" class="btn btn-primary">@DateTime.Now.Year</a><br><br>
    <a  href="#@DateTime.Now.AddYears(-1).Year" class="btn btn-primary">@DateTime.Now.AddYears(-1).Year</a><br><br>
    <a  href="#@DateTime.Now.AddYears(-2).Year" class="btn btn-primary">@DateTime.Now.AddYears(-2).Year</a>
</div>
<script>
  // without a
$(".btn").click(function(e){
e.preventDefault();
 console.log(this);
alert("click");
});
</script>
</body>
</html>
&#13;
&#13;
&#13;