简体   繁体   English

在函数中获取元素

[英]Get element within function

I did: 我做了:

var element = document.getElementById('myelement');

Now I want to do: 现在我想做:

 element.myFunction();

but I have no idea how to get the element within the function. 但是我不知道如何在函数中获取元素。 How do I do this? 我该怎么做呢?

function myFunction() {
// Get element here?
}

In javascript since you are declaring 在JavaScript中,因为您要声明

var element = document.getElementById('myelement');

You already have the element in the global scope, so you can simply call it inside your function 您已经在全局范围内拥有该元素,因此您可以在函数内部简单地调用它

function myFunction() {
  // Do something with your element
}

EDIT: If you're instead declaring your element inside another function or if you want to use the same function for different elements, you must use a parameter. 编辑:如果要在另一个函数中声明元素,或者要对不同元素使用相同的函数,则必须使用参数。 This is the call: 这是电话:

myFunction(element)

And this is the function 这就是功能

function myFunction(element) {
  // Do something with your element
}

If you want to chain your your function with the element, then you need to extend the prototype of the HTMLElement , or Node , objects: 如果要将函数与元素链接,则需要扩展HTMLElementNode对象的原型:

HTMLElement.prototype.myFunction = function (parameters) {
    var elementToActOn = this;
    elementToActOn.style.color = 'green';
    return this; // for further chaining
}

Or: 要么:

Node.prototype.myFunction = function (parameters) {
    var elementToActOn = this;
    elementToActOn.style.color = 'green';
    return this; // for further chaining
}

With this approach this , inside the myFunction() method, will refer to the element selected by: 通过这种方法, myFunction()方法内部的this将引用由以下元素选择的元素:

document.getElementById('elementID').myFunction();

JS Fiddle demo , using the HTMLElement prototype. JS Fiddle演示 ,使用HTMLElement原型。

JS Fiddle demo , using the Node prototype. JS Fiddle演示 ,使用Node原型。

Similarly, if all you want to do is pass the element-node to the function without 'explicitly' passing it as an argument: 同样的,如果你想要做的就是将元素节点的功能,无需“明确”它作为参数传递:

function myFunction () {
    this.style.color = 'red';
}

document.getElementById('elementID').addEventListener('click', myFunction);

JS Fiddle demo . JS小提琴演示

If you'd prefer to act on multiple elements, selected by getElementsByTagName() , getElementsByClassName() or querySelectorAll() (among others), then you'd need, instead, to extend the NodeList prototype, for example: 如果您希望对由getElementsByTagName()getElementsByClassName()querySelectorAll() (以及其他)选择的多个元素进行操作,则需要扩展NodeList原型,例如:

NodeList.prototype.myFunction = function (parameters) {
    var elements = this;
    [].forEach.call(elements, function(a){
        a.style.color = 'green';
    });
    return this; // for chaining
}

/* calling the function, with a simple demonstration of why you might want to
   chain, by returning 'this': */
var len = document.getElementsByClassName('elementClass').myFunction().length;
console.log(len);

JS Fiddle demo . JS小提琴演示

You can add a custom function to the prototype of HTMLElement objects like this: 您可以像这样将自定义函数添加到HTMLElement对象的原型中:

HTMLElement.prototype.customFunc = function(){
    // within this function, 'this' will refer 
    // to the element that it was called on
};

This means that any element will have access to the customFunc function as a method. 这意味着任何元素都可以作为方法访问customFunc函数。 For example: 例如:

HTMLElement.prototype.customFunc = function(){
    console.log(this.id);
};

// now assuming your HTML contains #myElement and #anotherElem:
document.getElementById('myElement').customFunc(); // displays 'myElement'
document.getElementById('anotherElem').customFunc(); // displays 'anotherElem'

Obviously, be careful with the naming of the function, as you probably don't want to overwrite any pre-existing methods or properties. 显然,请谨慎使用该函数的名称,因为您可能不想覆盖任何现有的方法或属性。

Is it what you want 是你想要的吗

    <input type = "button" value = "Next" id = "btnNext" />

    <script>
    HTMLElement.prototype.myFunction = function()
    {
        alert(this.id);
    }

    var elem = document.getElementById("btnNext");
    elem.myFunction();

    </script>

Given 给定

var element = document.getElementById('myelement');

It looks like you want to have a function using the this keyword 看起来您想使用this关键字来具有功能

function myFunction() {
    console.log(this); // logs `this` (which will be `element`)
}

And rather than setting a property so you could element.myFunction(); 而且,与其设置属性,不如设置element.myFunction(); , I'd suggest using Function.prototype.call or Function.prototype.apply , ie ,我建议使用Function.prototype.callFunction.prototype.apply ,即

myFunction.call(element); // element gets logged

rather u should try this , i will give an example for a div with onclick 相反,您应该尝试一下,我将通过onclick给出一个div的示例

<script>

function myfunc(){
getElementById('sample').whatever function u want
}
</script>

And in the body u can use - 在体内,您可以使用-

<body>
<div id="sample" onclick="myfunc()">The function will happen onclicking the div</div>
</body>

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

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