I have multiple links in my page rendered from the database. All of them I gave the same ID and created an JQuery click function taking from that id. Im trying to run a simple test calling an alert but it doesn’t work. Ins’t it suppose to work? Is there a better approach?
$("#lkResumeIt").click(function () {
alert("resume it");
});
<a id='lkResumeIt' href='#' contentID='1'>Item 1</a>
<a id='lkResumeIt' href='#' contentID='18'>Item 2</a>
<a id='lkResumeIt' href='#' contentID='22'>Item 3</a>
...
The code below using class selector workd fine when the elements are static, but when they are dynamically they dont. see actual code below:
<script language="javascript">
$("#divContent").on('click', 'a.linky', function (event) {
alert("resume it");
});
function RunIt() {
$("#divContent").html("");
var jsongo = '';
$.ajax({
type: 'POST',
url: '/Controller/FollowingPaused/',
data: jsongo,
success: function (msg) {
for (i = 0; i < msg.length; i++) {
var htmlCode = "<a href='/Controller/Details/" + msg[i].ID + "' style = 'float: left;'><img class='packageImage' border='0' src='" + msg[i].Size0Path + "' /></a>";
htmlCode += "<span style='float: left;margin: 5px 0px 0px 10px;'>" + "<b>" + msg[i].TheName + "</b><br>";
if (msg[i].IsPaused == true) {
//htmlCode += "<a href='/Controller/Resume/" + msg[i].ID + "'>Resume</a>";
htmlCode += "<a href='#bar' class=linky contentID='" + msg[i].ID + "'>Resume</a>";
} else {
//htmlCode += "<a href='/Controller/Pause/" + msg[i].ID + "'>Pause</a>";
htmlCode += "<a href='#bar' class=linky contentID='" + msg[i].ID + "'>Pause</a>";
}
htmlCode += "</span>";
htmlCode += "<div class='clear'></div>";
$("#divContent").append(htmlCode);
}
}
});
}
RunIt()
</script>
<div style="display: table-row;">
<div id="divContent" style="display: table-cell; line-height: 1.5;">
</div>
</div>
IDs cannot be duplicated. If you want one hook for jQuery, use
class, which CAN be duplicated.Example:
HTML:
<a href="#bar" class="linky">Foo</a>JavaScript:
For dynamically-created elements: