动态锚标记到DIV但CSS单击不起作用

时间:2011-12-01 09:47:37

标签: jquery css

我有下面的代码片段当我点击链接时遇到问题,即1,2,3,4号码点击无法正常工作......没有发生任何事情。

脚本

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        var number = 0;
        number = number+1;

        var numhtml = "<a href='#' rel='"+number+"'>"+number+"</a>"
        $("#slidenumbers").append(numhtml);

        $(".paging a").click(function() {   
            $active = $(this); //Activate the clicked paging
            //Reset Timer
            clearInterval(play); //Stop the rotation
            rotate(); //Trigger rotation immediately
            rotateSwitch(); // Resume rotation
            return false; //Prevent browser jump to link anchor
        }); 

    });
</script>

<div class="paging" id="slidenumbers"></div>

CSS

.paging a {
    padding-top: 2px;
    padding-left:5px;
    padding-right:5px;
    padding-bottom:3px;
    text-decoration: none;
    color: #fff;
    background: #DAF3F8;
    border: 1px solid gray;
}

.paging a.active {
    color:white;
    font-weight: bold; 
    background: #5DC9E1; 
    border: 1px solid gray;
    -moz-border-radius: 3px;
    -khtml-border-radius: 3px;
    -webkit-border-radius: 3px;
}

.paging a:hover {
    color:white;
    font-weight: bold; 
}

错误:

当我点击链接时,没有任何事情发生。你能帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

问题是因为click()处理程序只将事件附加到加载时可用的DOM元素。因为您要动态追加元素,所以如果您使用的是jQuery 1.7+,则需要使用on()附加事件,如果是1.6或更早版本,则需要使用delegate()

jQuery 1.7 +:

$(".paging").on('click', 'a', function() {   
    $active = $(this); //Activate the clicked paging
    //Reset Timer
    clearInterval(play); //Stop the rotation
    rotate(); //Trigger rotation immediately
    rotateSwitch(); // Resume rotation
    return false; //Prevent browser jump to link anchor
}); 

jQuery 1.6或更早版本:

$(".paging").delegate('click', 'a', function() {   
    $active = $(this); //Activate the clicked paging
    //Reset Timer
    clearInterval(play); //Stop the rotation
    rotate(); //Trigger rotation immediately
    rotateSwitch(); // Resume rotation
    return false; //Prevent browser jump to link anchor
}); 

答案 1 :(得分:0)

您的点击事件不会触发已动态添加到DOM的元素,您需要liveondelegate

$(".paging").on('click', 'a', function() {

$("a .paging").live("click", function() {   

答案 2 :(得分:0)

在动态添加元素时,您应该使用livedelegate函数:

$(".paging a").live('click', function() {   
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation
        return false; //Prevent browser jump to link anchor
    }); 

});