2012-02-04 73 views
2

我想我的脚本检查textarea盒子,当用户点击它,如果它有值“在这里添加附加信息!”使该框变为空白并将文本颜色更改为#000。它从灰色开始。基本JavaScript功能不起作用

的JavaScript

function changeMessage() { 
    if(this.value=='Add additional information here!') 
      {this.value='';this.style.color='#000';} 
} 

HTML

<textarea name="message" id="message_input" rows="4" cols="21" maxlength="200" 
      onfocus="changeMessage();" 
      onblur="changeMessageBack();" 
      >Add additional information here!</textarea> 

回答

2

changeMessage()背景下,this并不是指你的文本区域。尝试通过在文本区域目标是这样的:

JS:

function changeMessage(obj) { 
    if(obj.value=='Add additional information here!') { 
     obj.value=''; 
     obj.style.color='#000'; 
    } 
} 

HTML

<textarea name="message" id="message_input" rows="4" cols="21" maxlength="200" 
      onfocus="changeMessage(this);" 
      onblur="changeMessageBack(this);" 
      >Add additional information here!</textarea> 

这里的a working fiddle证明。

附加信息:

+0

雅的作品。我认为这总是指它所处的元素? – noWayhome 2012-02-04 18:29:13

+0

@noWayhome:它的确如此,但是你的''changeMes​​sage(this);“'成为匿名函数的主体,所以它在*函数中指出这个元素。当你从另一个内部调用一个函数时,JavaScript不会自动在你调用的函数中设置this this到当前值。您需要手动执行此操作。来自@xdazz的[answer](http://stackoverflow.com/a/9143288/1106925)展示了如何。用于'.call()'的+1 – 2012-02-04 18:40:52

2

当您在全球范围内被称为changeMessage(),该this指的window对象,而你可以告诉运行的这个规定的呼叫值利用.call工作。

变化onfocus="changeMessage();"onfocus="changeMessage.call(this);"

+0

+1。 – 2012-02-04 18:38:18

+0

@詹姆希尔:如果你对投票的答案没有提供解释,那么为什么只是这个答案?你为什么不投票否决不提供解释的其他答案? – 2012-02-04 18:45:52

+0

@詹姆希尔你说得对。添加了一些解释。 :) – xdazz 2012-02-04 18:50:04

1

您也可以使用占位符属性无javascript:

<input type="text" name="the_name" placeholder="Add additional information here!">