2013-02-11 61 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