当我使用模板时,Javascript函数不起作用

时间:2013-08-07 12:56:47

标签: javascript jquery ajax

我有一个带有javascript代码的html文件。

<div id="star_rating">
    <a id="one">&#9734;</a><a id="two">&#9734;</a><a id="three">&#9734;</a>
</div>
<script type="text/javascript">
$(document).on("ready", function() {
    $("#one").hover(
        function () {
            markHover("true", "false", "false", "false", "false");
        },function () {
            markHover("false", "false", "false", "false", "false");
        }               
    );
    $("#two").hover(
        function () {
            markHover("true", "false", "false", "false", "false");
        },function () {
            markHover("false", "false", "false", "false", "false");
        }               
    );
});

这很有效。现在我使用jQuery模板系统。在index.html中包含脚本标记。在包含.on("pagebefore")事件的其他文件中,我包含了三个a标记。问题是.hover函数不起作用。当我在我的控制台中粘贴.hover代码时,它可以正常工作。

这里是jsFiddle

感谢您的建议!

2 个答案:

答案 0 :(得分:1)

可能是因为元素是动态创建的

$(document).on('mouseenter','#one',function () {
    markHover("true", "false", "false", "false", "false");
}).on('mouseleave', '#one', function () {
    markHover("false", "false", "false", "false", "false");
});
$(document).on('mouseenter','#two',function () {
    markHover("true", "true", "false", "false", "false");
}).on('mouseleave', '#two', function () {
    markHover("false", "false", "false", "false", "false");
});

您可以将其简化为

var params = {
    'one': ["true", "false", "false", "false", "false"],
    'two': ["true", "true", "false", "false", "false"],
    'three': ["true", "true", "true", "false", "false"],
    'four': ["true", "true", "true", "true", "false"],
    'five': ["true", "true", "true", "true", "true"],
}

$(document).on('mouseenter','#one, #two, #three, #four, #five',function () {
    markHover.apply(window, params[this.id]);
}).on('mouseleave', '#one, #two, #three, #four, #five', function () {
    markHover("false", "false", "false", "false", "false");
});

演示:Fiddle

答案 1 :(得分:1)

代码太多代码,不知道为什么它不能与你的模板一起工作但是试试这个:

jQuery的:

   $(".rate").hover(
        function () {
            var thisone = parseInt($(this).data('star'));
            $(".rate").each(function(){ 
                if(parseInt($(this).data('star')) <= thisone)
                {
                    $(this).html("&#9733;");
                }
            });
        },
        function () {
            $(".rate").each(function(){
                $(this).html("&#9734;");
            });
        }               
    );

HTML:

<div>
    <a class="rate" id="one" data-star="1">&#9734;</a>
    <a class="rate" id="two" data-star="2">&#9734;</a>
    <a class="rate" id="three" data-star="3">&#9734;</a>
    <a class="rate" id="four" data-star="4">&#9734;</a>
    <a class="rate" id="five" data-star="5">&#9734;</a>
</div>

小提琴演示:http://jsfiddle.net/calder12/uXPt9/3/

相关问题