点击添加背景颜色

时间:2013-05-28 07:04:16

标签: javascript jquery django-templates

我的django模板中有动态li

<script type="text/javascript" language="javascript">
    function setSize(size) {
        document.getElementById('id_option1').value = size;
    }

    function notavailable(notavai) {
        alert('selected product is not available');
    }
</script>


{% for i in prosize %}
    {% if i.num_in_stock > 0 %}
        <li><a id="{{i.option1}}1" ref="javascript:setSize('{{i.option1}}')">{{i.option1}}</a></li>
    {% endif %}
{% endfor %}

我需要将背景 * 颜色 *添加到有效 链接 onclick 已经在a上使用javascript函数。请告诉我该怎么做

3 个答案:

答案 0 :(得分:2)

Working jsFiddle Demo

所以,很容易,在HTML标记中你有:

<a class="order" id="{{i.option1}}" href="javascript:setSize('{{i.option1}}')">{{i.option1}}</a>
  • 请注意,我已更改id。我从最后删除了1
  • 您编写的href属性也无效。我纠正了。
  • 此外,我已经为它添加了一个课程以供更进一步使用。

将您的setSize功能更改为:

// because IE9 (and below) doesn't support for getElementsByClassName
// we use this funciton instead
// written by Jonathan Snook
// http://snook.ca/archives/javascript/your_favourite_1
function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function setSize(size) {
    // i just comment this line as i don't know what it doesyourself
    // document.getElementById('id_option1').value = size;

    // change the color the others to transparent
    var others = getElementsByClassName(document, 'order');
    for (var i = 0, l = others.length; i < l; i++) {
        others[i].style.backgroundColor = 'transparent';
    }

    // this line will change the background color of your element
    document.getElementById(size).style.backgroundColor = '#ff6600';
}

的jQuery

如果您使用的是jQuery,则无需在内部使用javascript,让jQuery为您处理所有这些内容。 将此代码写在.js文件中:

$(function () {
    // get al links and attach the `click` handler to them
    $('.order').on('click', function (e) {
        // prevent default behaviour of link
        e.preventDefault();

        // get size and do something with it
        var size = $(this).attr('data-size');
        $('#textbox').val(size);

        // change the color the others to transparent
        $('.order').css('background-color', 'transparent');

        // change the color of link
        $(this).css('background-color', '#ff6600');
    });
});

答案 1 :(得分:0)

你想要的不应该在javascript或python中实现,而是CSS。您应该在CSS中使用:active选择器。

http://www.w3schools.com/cssref/sel_active.asp

答案 2 :(得分:0)

在你的循环中,你也可以绑定点击事件并传递id ......如

{% for i in prosize %}
    {% if i.num_in_stock > 0 %}
        <li><a id="{{i.option1}}1" onclick='ChangeColor('+{{i.option1}}1+')' ref="javascript:setSize('{{i.option1}}')">{{i.option1}}</a></li>
    {% endif %}
{% endfor %}

function ChangeColor(id)
{
    $("#"+id).css("background","#fff");
}