動作中の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');
});
});