javascript this.value不起作用? [英] javascript this.value doesn't work?

查看:136
本文介绍了javascript this.value不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起要问那个傻瓜:D但是我在这里做错了什么?

sorry for asking that stupid:D However what did i do wrong here?

html:

<div onclick="prompt()" value="test">test</div>

javascript:

javascript:

function prompt() {

    var error = this.value;
    alert("sdsd");

}

谢谢!

推荐答案

首先,< div> s没有属性,因此 .value 将无效。其次,你应该使用内联JavaScript。

First off, <div>s don't have a value attribute, so .value won't work. Second, you should not use inline JavaScript.

你应该做的是:

<div id="test" value="test">test</div>

然后:

$(function(){
    $('#test').click(function(){
        // You need to get the attribute from the element
        var error = $(this).attr('value');
    });
});

如果您必须使用内联事件,那么您需要元素传递给 prompt()函数。问题是它不知道这个是什么。这就是你应该绑定事件的原因,如上所示。无论如何,你也可以这样做:

If you must use inline events, then you need to pass the element to the prompt() function. The problem is that it doesn't know what this is. This is why you should bind the event as shown above. Anyway, you can also do:

<div onclick="prompt(this)" value="test">test</div>

然后:

function prompt(ele){
    // You can't use `.value` because `<div>`s
    // don't have a value property
    var error = ele.getAttribute('value');
}

P.S。我是否还建议使用数据 - * 属性来代替无效属性?

P.S. May I also suggest using data-* attributes for this instead of invalid attributes?

<div id="test" data-value="test">test</div>

然后:

$(function(){
    $('#test').click(function(){
        var error = $(this).data('value');
    });
});

这篇关于javascript this.value不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆