2014-08-28 150 views
0

我正在通過ajax將值生成到表中。這個值是s。 這個角色裏面有一個錨點,這個角色就是所有這些角色。這個錨標籤有一個類,我用它來引用它與JavaScript。在javascript中獲取動態生成元素的屬性值(通過ajax)

在這個角色的定位標記有一個onclick功能指引JavaScript方法,我想用這個方法來獲取點擊的定位標記的屬性之一。 但不幸的是,當我點擊角色中的錨標籤時,我得到了未定義的錯誤。

<tr> 

<td> 
         <a href="#" onClick="JavaScript:filltransfercombo();" class="btn btn-default transferchat" data-operatorid="@avisitor.OperatorID" data-toggle="modal" data-target="#transferModal" title="Transfer chat"> 
          <img src="~/Content/images/chaticons/transfer.png" height="20" width="20" /> 
         </a> 
        </td> 

</tr> 

我的意圖是收集此屬性 - data-operatorid。我想在我的JavaScript中使用它進行一些操作。

我的JavaScript低於

<script type="text/javascript"> 

function filltransfercombo() { 


      var result = ""; 
      var active = $('a').index(this); 
      var currentoperatorid = $(active).attr("data-operatorid"); //This is the id of the currently attending operator 

      console.log(currentoperatorid); 

     } 

</script> 
+0

我覺得你很困惑jQuery和ajax。 – SimpleJ 2014-08-28 15:46:59

+0

你是怎麼意思@SimpleJ – user3576600 2014-08-28 15:47:28

+0

我試圖用jquery中的on()方法來獲取當前點擊元素的屬性。但方法沒有觸發。所以我覺得我應該使用javascript – user3576600 2014-08-28 15:48:49

回答

1

onclick事件不需要javascript:符號......你會把它放進萬一你設置方法上href

另外,從onclick事件中,您將有權訪問this變量,而不是來自該方法。你可以,但是,把它作爲一個參數,因此:

<a href="#" onClick="filltransfercombo(this);" class="btn btn-default transferchat" data-operatorid="@avisitor.OperatorID" data-toggle="modal" data-target="#transferModal" title="Transfer chat"> 

和JS:

function filltransfercombo(sender) { 
    var result = ""; 
    var currentoperatorid = $(sender).attr("data-operatorid"); //This is the id of the currently attending operator 

    console.log(currentoperatorid); 

} 
+0

你剛剛爲我節省了一小時的編碼。 – user3576600 2014-08-28 15:53:18

+0

非常感謝。它像魔術一樣運作,一切都很順利。你是布魯姆兄弟。我很感激。 @LcSalazar – user3576600 2014-08-28 15:54:17

+0

如果這個屬性是一個'data..'標籤,那麼使用'$(sender).data(「operatorid」);''會不會更高效/正確? – entropic 2014-08-28 15:55:13

0

這可以很容易地使用jQuery來完成。

你的錨卸下「點擊」屬性,而是綁定點擊功能的錨標籤(僅在表內)。然後在該函數中添加處理代碼。

做這樣的事情:

<script type="text/javascript"> 
$(document).ready(function() { 
    $('table tr td a').click(function() { 
     var result = ""; 
     var currentoperatorid = $(this).data("operatorid"); //This is the id of the currently attending operator 

     console.log(currentoperatorid); 
    }); 
}); 
</script> 

自然地,你需要確保JavaScript庫也包含此頁上的jQuery的。

相關問題