JQuery 如何用另一个包含事件处理程序的元素来扩展一个元素?

发布于 2024-12-05 17:13:28 字数 395 浏览 1 评论 0原文

是否有解决方案来创建一个虚拟元素及其属性、方法和事件处理程序,并用它扩展现有元素? 例如:

var dummyElement = $('<div />', {
  // properties
  ...
  // methods
  ...
  // event handlers
  ...
});

然后,

$.extend( $('#myElement'), dummyElement );

现在,$('#myElement') 除了它自己的属性、方法和事件处理程序之外,还具有 dummyElement 的属性、方法和事件处理程序。

是否可以?我怎样才能用 JQuery 做到这一点?

谢谢

Is there a solution to create a dummy element with its properties, methods and event handlers and extend an existing element with it ?
For example :

var dummyElement = $('<div />', {
  // properties
  ...
  // methods
  ...
  // event handlers
  ...
});

and then,

$.extend( $('#myElement'), dummyElement );

Now, $('#myElement') has the dummyElement's properties, methods and event handlers, in addition to its own.

Is it possible? How could I do that with JQuery ?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尸血腥色 2024-12-12 17:13:28

IMO 你根本不需要虚拟元素。在下面的示例中,我演示了一种在纯 J​​avaScript 中创建元素的简单方法。

源代码

createElement: function (options) {
    /// <summary>Creates a document object model (DOM) element.</summary>
    /// <param name="options" type="Object">An object that contains tag name, attributes, events, properties and children.</param>

    var clone = this.extend({}, options);

    // Create element
    var e = document.createElement(clone.tag);
    delete clone.tag;

    // Assign attributes
    if (clone.attributes) {

        for (var attrib in clone.attributes) {
            e.setAttribute(attrib.replace('

您可以使用 jQuery 重写上述代码来扩展您的元素,而不是创建一个新元素。

使用

Util.createElement({
    tag: 'input',
    type: 'checkbox',
    checked: this.checked,
    events: {
        change: function(e) { // ... }
    }
});
, ''), clone.attributes[attrib]); } delete clone.attributes; } // Create and append children if has if (clone.children) { for (var idx in clone.children) { e.appendChild(this.createElement(clone.children[idx])); } delete clone.children; } // Assign event handlers if (clone.events) { for (var en in clone.events) { var handler = clone.events[en]; if (handler instanceof Function) this.addHandler(e, en, handler); } delete clone.events } // Assign properties for (var prop in clone) { e[prop] = clone[prop]; } return e; }, addHandler: function (element, eventName, handler) { // Firefox is first, Of cource after chrome :p if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else if (element.attachEvent) { element.attachEvent('on' + eventName, handler); } }, extend: function (expando, properties, override) { if (properties && typeof (properties) == 'object') { for (var prop in properties) { var val = properties[prop]; if (!expando[prop] || override) expando[prop] = val; } } return expando; }

您可以使用 jQuery 重写上述代码来扩展您的元素,而不是创建一个新元素。

使用

IMO you don't need a dummy element at all. In following example I demonstrates a simple way to create an element in pure javascript.

Source Code

createElement: function (options) {
    /// <summary>Creates a document object model (DOM) element.</summary>
    /// <param name="options" type="Object">An object that contains tag name, attributes, events, properties and children.</param>

    var clone = this.extend({}, options);

    // Create element
    var e = document.createElement(clone.tag);
    delete clone.tag;

    // Assign attributes
    if (clone.attributes) {

        for (var attrib in clone.attributes) {
            e.setAttribute(attrib.replace('

You can rewrite the above code with jQuery to extend your element, instead of creating a new one.

Usage

Util.createElement({
    tag: 'input',
    type: 'checkbox',
    checked: this.checked,
    events: {
        change: function(e) { // ... }
    }
});
, ''), clone.attributes[attrib]); } delete clone.attributes; } // Create and append children if has if (clone.children) { for (var idx in clone.children) { e.appendChild(this.createElement(clone.children[idx])); } delete clone.children; } // Assign event handlers if (clone.events) { for (var en in clone.events) { var handler = clone.events[en]; if (handler instanceof Function) this.addHandler(e, en, handler); } delete clone.events } // Assign properties for (var prop in clone) { e[prop] = clone[prop]; } return e; }, addHandler: function (element, eventName, handler) { // Firefox is first, Of cource after chrome :p if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else if (element.attachEvent) { element.attachEvent('on' + eventName, handler); } }, extend: function (expando, properties, override) { if (properties && typeof (properties) == 'object') { for (var prop in properties) { var val = properties[prop]; if (!expando[prop] || override) expando[prop] = val; } } return expando; }

You can rewrite the above code with jQuery to extend your element, instead of creating a new one.

Usage

心在旅行 2024-12-12 17:13:28

查看 jQuery 的 clone() 方法。与 replaceWith() 结合使用,我认为您可以完成类似的事情(但不完全是)您要查找的内容:

// 1- create dummy
var dummy - $('<div />');

// 2- add stuff to dummy...
// ex: adding a click handler, and an "alt" attribute
dummy.click(function(evt) { console.log("click"); }
dummy.attr("alt", "this is the alt text for dummy");

// 3- clone dummy, and the replace `#myElement` with the clone
$('#myElement').replaceWith( dummy.clone(true) );

注意:在示例中创建 dummyElement 时使用的代码不是 jQuery 函数。据我所知,您不能仅通过将属性、方法和处理程序作为第二个参数传递给 jQuery 函数来添加它们。如果您确实传递了第二个参数,jQuery 会将其解释为解析选择器的上下文。我展示了添加单击处理程序和属性的示例。


编辑:如果您只是尝试将对象属性(如您所说:“属性”、“方法”和“事件处理程序”)从一个 HTML 元素复制到另一个 HTML 元素,则 $ .extend(...) 是完成这项工作的工具。只需确保您正在操作 HTML 元素本身,而不是 Jquery 集对象。看起来像这样:

var dummy = $('<div />');
var myElement = $('#myElement');
$.extend(myElement.get(0), dummy.get(0));

Check out jQuery's clone() method. In conjunction with replaceWith(), I think you can accomplish something close to (but not exactly) what you're looking for:

// 1- create dummy
var dummy - $('<div />');

// 2- add stuff to dummy...
// ex: adding a click handler, and an "alt" attribute
dummy.click(function(evt) { console.log("click"); }
dummy.attr("alt", "this is the alt text for dummy");

// 3- clone dummy, and the replace `#myElement` with the clone
$('#myElement').replaceWith( dummy.clone(true) );

Note: the code you've used when creating dummyElement in your example, is not a valid form of the jQuery function. As far as I know, you can't add properties, methods, and handlers by just passing them as a second argument to the jQuery function. If you do pass a second argument, jQuery will interpret this as a context in which to resolve the selector. I've shown an example of adding a click handler, and an attribute.


Edit: If you're just trying to copy object properties (as you said: "properties", "methods", and "event handlers") from one HTML Element to another, then $.extend(...) is the tool for the job. Just be sure you're operating on the HTML Elements themselves, not the Jquery set objects. That'll look something like this:

var dummy = $('<div />');
var myElement = $('#myElement');
$.extend(myElement.get(0), dummy.get(0));
稳稳的幸福 2024-12-12 17:13:28

好的。感谢不同的答案,特别是来自Lee的答案。
看起来 $.extend(...) jQuery 方法并不是为了从另一个 DOM 元素扩展一个 DOM 元素而设计的。但它可以从对象扩展 DOM 元素。这是一个解决方案:

1)首先我创建扩展对象。每个扩展都必须定义一个 initExtension() 方法。下面是创建两个扩展对象的示例:

var myObjExtension1 = {
  // constructor
  initExtension : function() {
    // Add some data properties
    this.something = 'something';

    // Add some method properties
    this.doSomething = function() { alert(this.something); };

    // Add some DOM elements
    $(this).append('<div>element created from extension 1</div>');  

    // Add some event handlers
    $(this).click(
      function(evt) {
        $(this).append('<div>element created from extension 1 click event</div>');
      }
    );
  }
};

var myObjExtension2 = {
  // constructor
  initExtension : function() {
    // Add some data properties
    this.more = 'more';

    // Add some method properties
    this.doMore = function() { alert(this.more); };

    // Add some DOM elements
    $(this).append('<div>element created from extension 2</div>');  

    // Add some event handlers
    $(this).click(
      function(evt) {
        $(this).append('<div>element created from extension 2 click event</div>');
      }
    );
  }
};

2) 为了轻松扩展我需要扩展的所有元素,我创建了一个小 jQuery 插件。该插件包含一种使用指定扩展名扩展源元素的方法:

(function($){
  $.fn.extendWith = function( objExtension ) {
    this.each( 
      function(index) {
        $.extend( this, objExtension );
        this.initExtension();
      }
    );
    return this; // jQuery chaining
  }
})(jQuery);

3) 最后,我扩展了一些 jQuery 元素。请注意,在下面的示例中,我通过链接扩展了与 someElement 类匹配的元素,首先使用 myObjExtension1,然后使用 myObjExtension2 extendWith(...) 插件方法:

$('.someElement').extendWith( myObjExtension1 ).extendWith( myObjExtension2 );

现在,所有 myObjExtension1myObjExtension2 数据属性、方法属性和事件处理程序可从我的 $('.someElement') 元素中获得。例子:

$('.someElement').each( function() {
  this.doSomething();
  this.doMore();
});

Ok. Thanks to the different answers, particularly from Lee.
It seems that the $.extend(...) jQuery method is not designed to extend a DOM element from another one. But it can extend a DOM element from an object. Here is a solution to do that :

1) First I create the extension objects. Each of these extensions must have an initExtension() method defined. Here is an example for creating two extension objects :

var myObjExtension1 = {
  // constructor
  initExtension : function() {
    // Add some data properties
    this.something = 'something';

    // Add some method properties
    this.doSomething = function() { alert(this.something); };

    // Add some DOM elements
    $(this).append('<div>element created from extension 1</div>');  

    // Add some event handlers
    $(this).click(
      function(evt) {
        $(this).append('<div>element created from extension 1 click event</div>');
      }
    );
  }
};

var myObjExtension2 = {
  // constructor
  initExtension : function() {
    // Add some data properties
    this.more = 'more';

    // Add some method properties
    this.doMore = function() { alert(this.more); };

    // Add some DOM elements
    $(this).append('<div>element created from extension 2</div>');  

    // Add some event handlers
    $(this).click(
      function(evt) {
        $(this).append('<div>element created from extension 2 click event</div>');
      }
    );
  }
};

2) In order to extend easily all the elements I need to extend, I created a little jQuery plug-in. This plug-in contains one method that extend the source element with the specified extension:

(function($){
  $.fn.extendWith = function( objExtension ) {
    this.each( 
      function(index) {
        $.extend( this, objExtension );
        this.initExtension();
      }
    );
    return this; // jQuery chaining
  }
})(jQuery);

3) Finally, I extend some jQuery elements. Note that in the following example, I extend the elements that match the someElement class, first with the myObjExtension1 and then with the myObjExtension2, by chaining the extendWith(...) plug-in method:

$('.someElement').extendWith( myObjExtension1 ).extendWith( myObjExtension2 );

Now, all the myObjExtension1 and myObjExtension2 data properties, method properties and event handlers are available from my $('.someElement') elements. Example:

$('.someElement').each( function() {
  this.doSomething();
  this.doMore();
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文