I have a set of dynamically generated anchor tags in a for loop as follows:

<div id = "solTitle"> <a href = "#"  id = "' + tagId + '" onClick = "openSolution();"> ' + solTitle + '</a></div> <br>';

执行此代码后,其中一个 case 的html输出如下所示:

<div id = "solTitle"> <a href = "#"  id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>

<div id = "solTitle"> <a href = "#"  id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>

Now I want different texts to be displayed on clicking the above links. openSolution() looks like this:

function openSolution() {
    alert('here');
    $('#solTitle a').click(function(evt) {
        evt.preventDefault();
        alert('here in');
        var divId = 'summary' + $(this).attr('id');

        document.getElementById(divId).className = '';

    });
}

When I execute it and click on either of the links, the flow doesnot come inside the jquery click handler. I checked it by the above alerts used. It only displays the alert - 'here' and not the alert - 'here in'. On clicking the link second time, everything works perfectly with correct value of divId.

推荐答案

The first time you click the link, the openSolution function is executed. That function binds the click event handler to the link, but it won't execute it. The second time you click the link, the click event handler will be executed.

What you are doing seems to kind of defeat the point of using jQuery in the first place. Why not just bind the click event to the elements in the first place:

$(document).ready(function() {
    $("#solTitle a").click(function() {
        //Do stuff when clicked
    });
});

This way you don't need onClick attributes on your elements.

It also looks like you have multiple elements with the same id value ("solTitle"), which is invalid. You would need to find some other common characteristic (class is usually a good option). If you change all occurrences of id="solTitle" to class="solTitle", you can then use a class selector:

$(".solTitle a")

由于duplicate id值无效,因此当面对同一个id的多个副本时,代码将无法正常工作.通常情况下,会使用第一个出现id的元素,而忽略所有其他元素.

Jquery相关问答推荐

即使我使用 [FromBody] C# 从视图(Ajax)发送请求时在控制器中收到 NULL 对象

jQuery:如何动态检测窗口宽度?

如何在 jQuery 中 Select 特定的表单元素?

模糊事件阻止点击事件工作?

JQuery通过类名获取所有元素

jQuery 动画滚动

TypeScript 中是否有this的别名?

Jquery Ajax,从 mvc.net 控制器返回成功/错误

清除并刷新 jQuery Chosen 下拉列表

用jquery查找div底部的位置

jQuery ajax 在 asp.net mvc 中上传文件

为不同的 node 类型配置jstree右键上下文菜单

为什么使用 jQuery on() 而不是 click()

如何使用 jquery 动态更改 iframe 中的内容?

JQuery:如果 div 可见

bootstrap 模式:关闭当前,打开新

如何在调用 Ajax 等异步调用时让代码等待

如何在按键事件后获取 jQuery .val()?

你会如何比较 jQuery 对象?

.animate() 的回调被调用两次 jquery