获取javascript中动态生成的元素(通过ajax)的属性值

getting values of attributes of dynamically generated elements (through ajax) in javascript

本文关键字:ajax 通过 属性 元素 动态 获取 javascript      更新时间:2023-09-26

我正在通过ajax将值生成到一个表中。这些值为s。在这个角色中有一个锚,它将在所有这些角色中。这个锚标记有一个类,我用它来用javascript引用它。

这个角色中的anchor标签有一个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>

我的意图是收集这个属性——数据运算符。我想在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>

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);
}

这可以通过jQuery轻松完成。

删除锚点上的"onClick"属性,而是将click函数绑定到锚点标记(仅在表中)。然后在该函数中添加处理代码。

这样做:

<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>

当然,您需要确保jQuery javascript库也包含在此页面中。