Javascript:onclick处理程序无法从<a> tag

时间:2018-01-24 15:11:14

标签: javascript

I have the following code in my html document

<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
         {% for type in types %}
             <li>
                 <a value="{{ type.name }}" onclick="addType(this)" >{{ type.name }}</a>
            </li>
         {% endfor %}
</ul>

A Django-template language loop provides the values for the < a > tags, and I have verified that {{ type.name }} != None

Yet the following function only prints out the 'raw html' for the tag.

function addType(e) {
    console.log(e);
    console.log(e.value);

}

The subsequent console.log of e.value returns an undefined. (Even when I replace the Django variable with something like 'IHaveaValue')

Does anyone know what I am doing wrong?

2 个答案:

答案 0 :(得分:3)

As you can see from their definition, anchors do not have a "value" property.您可以使用自己的数据属性,例如:

<a data-val="{{ type.name }}" onclick="addType(this)" >{{ type.name }}</a>

然后

 console.log(e.getAttribute('data-val'));

为了更完整,属性是元素固有的,而属性可以由用户定义。实际上,虽然您无法访问锚的e.value(即属性),但如果使用e.getAttribute('value')定义它,则可以访问值“attribute”。但为了避免混淆,创建自定义“数据属性”是一种更简洁的方法。

答案 1 :(得分:1)

您是否想要获取锚点的文本值?如果是这样,innerHTML会给你这个。

&#13;
&#13;
function addType(e) {
    console.log(e);
    console.log(e.innerHTML);

}
&#13;
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
         {% for type in types %}
             <li>
                 <a value="{{ type.name }}" onclick="addType(this)" >{{ type.name }}</a>
            </li>
         {% endfor %}
</ul>
&#13;
&#13;
&#13;