工作 jsFiddle 演示
所以,很容易,在 HTML 标记中你有:
<a class="order" id="{{i.option1}}" href="javascript:setSize('{{i.option1}}')">{{i.option1}}</a>
- 请注意,我已经更改了
id
. 我删除了1
它末尾的 from 。
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');
});
});