2014-08-28 151 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的。

相关问题