Add a link via jquery and have it call a jquery function

advertisements

I have a link that gets added prior to the page getting loaded. here's the code:

<script type="text/javascript" language="javascript">

    myLink= '<a href="#" id="test" class="test" value="1">SomeLink</a>';
    $("#Control").append(myLink);

    $(document).ready(function() {
        $("a").click(function() {
            Id = $(this).attr("value");
            ShowId(Id);
        });

When the page is finished loading have verified that the links show up correctly. The problem is when I click on the link the function doesn't get called. if I click on any other links that are part of the original page and haven't been added via jquery, the function gets called. The behavior is the same if I use $("#test") instead.

Is there something different I have to do for when I add a link through jquery?

Thanks in advance.


Maybe this is the most correct way:

$(function() {
    $("<a />", {
        href: "#",
        id: "test",
        className: "test",
        text: "SomeList"
    }).data("value", "1").on("click", function() {
        var id = $(this).data("value");
        // ...
    }).appendTo("#Control");
});

Note, that value attribute is not valid for anchor elements, so I suggested to use data for that.

DEMO: http://jsfiddle.net/N3vKS/