2013-02-11 62 views
0

我想在动态创建对象时处理对象的属性。动态创建时操作对象的属性

在下面给出的代码中,我想通过调用对象的相应函数来增加类似属性。然而,元件被动态创建和传递的onclick功能将仅参考锚标记。

这个想法与此论坛类似,其中每个问题都有可以批准或不批准的各种想法。我怎样才能独立操作每个对象的属性?

function idea(idea) { 
    this.ideatext = idea; 
    this.like = 0; 
    this.str = "\ 
    <div class = 'entered'> \ 
     <div class = 'text'> " + this.ideatext + "</div> \ 
     <div class = 'anchors'> \ 
      <a href = '' onclick = 'increase()'> Approve </a> \ 
      <a href = '' onclick = 'decrease()'> Disapprove </a> \ 
     </div> \ 
    </div>"; 

    this.increase = function() { 
     this.like++; 
    } 
    this.decrease = function() { 
     this.like--; 
    } 
} 

var ideaobj1 = new idea(someidea1); 
var ideaobj2 = new idea(someidea2); 
+0

您将需要以某种方式将动态创建的元素绑定到它要操作的对象。 – techfoobar 2013-02-11 12:40:26

+0

将元素添加到文档中,然后选择它并修改其属性,添加事件处理... – TheBronx 2013-02-11 12:42:48

回答

0

除了添加onclick属性,给标签一个类(我在这个例子中使用类增加和减少)。然后添加下面的jQuery代码

$(document) 
.on('click', '.increase', function() { 
    alert('increase function'); 
}); 
.on('click', '.decrease', function() { 
    alert('decrease function'); 
}); 
+0

是否不会影响所有具有增加类属性的对象? – Mellkor 2013-02-11 13:00:52

1

如果动态地创建JavaScript代码,你希望它是指其他的JavaScript代码,你必须知道的变量名。没办法。

<script type="text/javascript"> 

    function idea(varName, text) 
    { 
     this.varName = varName; 
     this.ideatext = text; 
     this.like = 0; 
     this.str = "\ 
     <div class = 'entered'> \ 
      <div class = 'text'> " + this.ideatext + "</div> \ 
      <div class = 'anchors'> \ 
       <a href = '' onclick = '" + this.varName + ".increase()'> Approve </a> \ 
       <a href = '' onclick = '" + this.varName + ".decrease()'> Disapprove </a> \ 
      </div> \ 
     </div>"; 

     this.increase = function() 
     { 
      this.like++; 
      return false; 
     } 
     this.decrease = function() 
     { 
      this.like--; 
      return false; 
     } 
    } 

    var wing = new idea("wing", "a wing is ..."); 
    var wheel = new idea("wheel", "a wheel is ..."); 

</script> 

并为创建的对象使用某种集中存储。也许是这样的:

var brain = new Object(); 
    brain["wing"] = new idea("brain.wing", "a wing is ..."); 
    brain["wheel"] = new idea("brain.wheel", "a wheel is ..."); 
+0

好的..假设我创建了2个物体 - 翼和轮。在屏幕上,我点击wing ** Approve **,这是如何引用WING对象的? @Creech – Mellkor 2013-02-12 06:25:26