嗨,我的 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 函数。请建议我如何执行此操作
最佳答案
所以,这很简单,在 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');
});
});
- 您可以查看jsFiddle demo .
关于javascript - 单击时添加背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16785757/