仅保存当前实例的对象值

Saving object value of only current instance

本文关键字:对象 实例 保存      更新时间:2023-09-26

尝试仅更改单个实例的对象值。

我试图制作一个小库,它可以做jQuery所做的一些事情,只是为了学习技巧。

我目前在将元素保留在对象中以供使用时遇到问题。

工作示例:

Brain('#test').html('a'); // this will change the innerHTML of #test with "a".

不工作示例:

var a = Brain('#test');
var b = Brain('#test2');
a.html('a'); // should change content of #test to "a", but changes content of #test2 to "a"

我的JS:

// create the brain function to select elements
var Brain = function(selector, context)
{
    if (typeof context == 'undefined')
        var context = document;
    Brain.elements = context.querySelector(selector);
    return Brain;
};
// set and get innerHTML of element
Brain.html = function(content)
{
    if (typeof content != 'undefined')
        Brain.elements.innerHTML = content;
    return Brain.elements.innerHTML;
};
// testing
var a = Brain('#test');
var b = Brain('#test2');
a.html('a');
b.html('b');

我的网页

<p id="test">test</p>
<p id="test2">test2</p>

JSFIDDLE 示例

嗨,

我刚刚浏览了你的代码。 循环旋转两次,并在 #test2 id 处结束。 这意味着Brain包含#test2元素 这就是第二个元素发生变化的原因。更改代码,如下所示,它正在工作

var a = Brain('#test').html('a');
var b = Brain('#test2').html('b');

快乐编码