无onclick的Javascript高亮显示效果

无onclick的Javascript高亮显示效果,javascript,Javascript,有没有一种方法可以更改div背景色(高亮显示),而不必在每次输入onclick中调用函数 下面是我的Javascript函数: <script type="text/javascript"> function highlight(element) { element.parentNode.style.backgroundColor = '#FF9900'; } function removeHighlight(element) { element.parentNode

有没有一种方法可以更改div背景色(高亮显示),而不必在每次输入onclick中调用函数

下面是我的Javascript函数:

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

功能突出显示(元素){
element.parentNode.style.backgroundColor='#FF9900';
}
函数removeHighlight(元素){
element.parentNode.style.backgroundColor='';
}
以下是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函数冲突。

您可以匿名将其绑定到该特定元素:

document.getElementById('foo').onclick = function() {
  this.parentNode.style.backgroundColor = '#FF9900';
}
但随后您将被迫使用
id
(比将相同的
onclick
代码编写20次要好)

如果要使用jQuery之类的JavaScript库,则此代码可以简化很多:

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

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

这将处理
中的所有
元素。不需要HTML中的任何内容。这一切都是在JS端完成的。

但像这样,他需要为每个输入元素编写此事件附件!您可以在元素上循环(如果它们共享一个公共类,则以某种方式循环),并以这种方式应用该处理程序。我也发布了一个jQuery解决方案来展示它是多么的简单。好吧,他可以将这个想法与一个定制结合在一起,并在
表单文本上使用它。如果我想使用YUI而不是jQuery任何想法呢?他们都可以相对轻松地做到这一点,但我从来没有使用过YUI。曾经