2011-06-04 41 views
1

有没有办法改变div背景颜色(突出显示)而无需在每次输入onclick中调用该函数?Javascript亮点效果没有onclick

这里是我的JavaScript函数:

<script type="text/javascript"> 
function highlight(element) { 
    element.parentNode.style.backgroundColor = '#FF9900'; 
} 
function removeHighlight(element) { 
    element.parentNode.style.backgroundColor = ''; 
} 
</script> 

这里是HTML:

<div class="form-item"> 
<label>Title:</label> 
<input class="form-text Title" 
     type="text" 
     onblur="removeHighlight(this);" 
     onfocus="this.value='';highlight(this);" 
     onselect="this.value='';" 
     onclick="this.value='';highlight(this);" 
     value="english" 
     name="Title"> 
<input class="form-text translations" 
     type="text" 
     onselect="this.value='';" 
     onclick="this.value='';" 
     value="translate" 
     name="title_translate"> 
</div> 

这里我的onclick或ONSELECT调用每个输入的功能,有时与其他JavaScript冲突功能在我的页面上。

回答

0

你可以匿名它绑定到特定的元素:

document.getElementById('foo').onclick = function() { 
    this.parentNode.style.backgroundColor = '#FF9900'; 
} 

但随后你将被迫使用id(比写相同onclick码20倍更好)。

如果你是使用JavaScript库如jQuery,这个代码可以简化不少:

$('div.form-item input').select(function() { 
    $(this).parent().css('background-color', '#FF9900'); 
}); 

$('div.form-item input').blur(function() { 
    $(this).parent().css('background-color', 'auto'); 
}); 

,将采取的照顾所有<div><input>元素。 HTML中不需要任何东西。这一切都在JS端完成。

+0

但是像这样,他需要为每个输入元素编写这个事件附件! – 2011-06-04 15:29:16

+0

您可以遍历元素(不知何故,如果它们共享一个公共类)并以这种方式应用该处理程序。我也发布了一个jQuery解决方案,以显示它是多么容易。 – Blender 2011-06-04 15:30:57

+0

那么,他可以将这个想法与一个自定义的[GetElementByClass](http://www.actiononline.biz/web/code/how-to-getelementsbyclass-in-javascript-the-code/)混合并在表单中使用它-text' – Lucas 2011-06-04 15:33:01