javascript - 单击时添加背景颜色

标签 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已经在 上使用 javascript 函数。请建议我如何执行此操作

最佳答案

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');
    });
});

关于javascript - 单击时添加背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16785757/

相关文章:

python - 为什么我覆盖的保存方法没有在我的 Django 模型中运行?

javascript - 无限缩放强制布局d3.js

jquery - $(window) 绑定(bind) hashchange 如何检查部分哈希更改?

javascript - 在点击时编写回调,如 jQuery

django - 如何在TemplateTag中获取request.user

python - “CsrfViewMiddleware”对象不可迭代

javascript - 在JavaScript中,为什么blur方法会触发blur事件,而submit方法不会触发submit事件?

javascript - Eslint: no-duplicates 解决错误:无法加载解析器 "node"

javascript - jQuery、insertBefore、验证、错误消息的放置

javascript - jquery中获取radio类型的输入字段的值