简体   繁体   English

从函数外部获取`this`

[英]Get `this` from outside a function

How, or is it even possible, to get the this value from a function? 如何,甚至可能从函数中获取this值? I've made this snippet which saves defaultValue on the function, but I would like to read this from outside the function, directly on the dom element. 我已经制作了这个片段,它在函数上保存了defaultValue ,但我想从函数外部直接在dom元素上读取它。 Is that possible?? 那可能吗??

I've made this, in jQuery: 我在jQuery中做了这个:

$("input").val(function() {
    var $label = $("label[for='" + $(this).attr("id") + "']");
    this.defaultValue = $label.text();
    $label.hide()
    return this.defaultValue
}).click(function() {
    if ($(this).val() == this.defaultValue) {
        $(this).val("");
    }
}).bind("blur", function() {
    if ($(this).val() == "") {
        $(this).val(this.defaultValue);
    }
});

See it in action here: http://jsfiddle.net/ZUZ3L/g6dMA/ 在这里看到它: http//jsfiddle.net/ZUZ3L/g6dMA/

You can save it to the element represented in the DOM with jQuery's .data() function: 您可以使用jQuery的.data()函数将其保存到DOM中表示的元素:

Do this on pageLoad: 在pageLoad上执行此操作:

$(this).data('defaultValue', $(this).val());

You can retrieve it later with: 您可以稍后检索它:

alert($('#myElement').data('defaultValue');

...which will return the value set at pageload, rather than the current value of the input. ...将返回pageload设置的值,而不是输入的当前值。

Inside your function $("input").val(function() { , this refers to one element from the $("input") query. 函数内部$("input").val(function() {this是指$("input")查询中的一个元素。
Note that $("input") will return a list of elements, even if only one exists. 请注意, $("input")将返回元素列表,即使只存在一个元素。 Use .get() to select an element. 使用.get()选择一个元素。
You can access defaultValue from $("input").get(0).defaultValue . 您可以从$("input").get(0).defaultValue访问defaultValue (assuming you only want one element) (假设你只想要一个元素)

尝试这个:

<input onfocus="if (this.value==this.defaultValue) this.value = '';" onblur="if (this.value=='') this.value = this.defaultValue;" name="search" value="Search">

Those functions are callback functions. 这些函数是回调函数。 Which means they are run when the event is fired, (from jQuery). 这意味着它们在事件被触发时运行(来自jQuery)。 So, this in this context is actually up to jQuery to decide.. in which case is the element to which the event is bound. 因此, this在这方面是居然高达jQuery来决定。在这种情况下,是该事件所绑定的元素。

On a side note, it looks like you are looking for the placeholder attribute (available only in HTML5, but you can find plugins for older browsers) 在旁注中,看起来您正在寻找占位符属性(仅在HTML5中可用,但您可以找到旧版浏览器的插件)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM