事件处理程序使用' this'关键字无法正常工作

时间:2015-07-18 12:44:56

标签: javascript html

标题可能不正确,但我不知道如何提出我的问题! 我遇到了this关键字的问题。在此代码<input type="text" onkeyup="this.value=this.value.toUpperCase();"></input>中使用它时 它完美地运作。但是当我在使用this关键字的输入元素上分配一个函数时,它不会像在
中那样工作 HTML

<input type="text" onkeyup="up();"></input>

的Javascript

function up()
{   
    this.value=this.value.toUpperCase();
}

3 个答案:

答案 0 :(得分:8)

这个这里不会是元素,你需要从DOM传递它,像这样使用它

<input type="text" onkeyup="up(this);"></input>

你的功能

function up(el)
{   
    el.value=el.value.toUpperCase();
}

答案 1 :(得分:1)

你也可以使用JavaScript提供的最可怕的东西:

ImageSpan imageSpan = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM) {
                public void draw(Canvas canvas, CharSequence text, int start,
                        int end, float x, int top, int y, int bottom,
                        Paint paint) {
                    Drawable b = getDrawable();
                    canvas.save();

                    int transY = bottom - b.getBounds().bottom;
                    // this is the key 
                    transY -= paint.getFontMetricsInt().descent / 2;

                    canvas.translate(x, transY);
                    b.draw(canvas);
                    canvas.restore();
                }
            };

onclick="up.call(this);" 基本上将函数内的call(...)设置为特定值,在本例中为元素。

答案 2 :(得分:0)

尝试使用函数扩展DOM元素原型:

HTMLInputElement.prototype.up = function() {
    if(this.type == "text") {
        this.value = this.value.toUpperCase();
    }
};
<input type="text" onkeyup="up();" placeholder="type something" />


但我严格建议你使用jquery,因为我不认为HTMLInputElement会一直存在于所有浏览器上:


$(function(){
  
  $('input.to-uppercase')
    .on('keyup', function(){$(this).val($(this).val().toUpperCase());});
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="text" class="to-uppercase" placeholder="write something">

相关问题