gpt4 book ai didi

javascript - 如何获取事件目标默认值 JavaScript

转载 作者:行者123 更新时间:2023-11-30 20:31:45 25 4
gpt4 key购买 nike

我需要能够获得目标的默认值。然而,它返回 undefined,即使它返回我编辑的文本内容。

表格

<table class="data  table-bordered table table-striped" id="ui" method="POST">
<tr style="background-color:blue;color:white;">
<td width="25%">Device-imei</td>
<td>Device-Model</td>
<td>device-nickname</td>
</tr>
<tr>
<td>"111111"</td>
<td>"Model"</td>
<td>
<div class="device-name" contenteditable>"Name"</div>
</td>
</tr>
<tr>
<td>"11121341"</td>
<td>"asdf"</td>
<td>
<div class="device-name" contenteditable>"Name"</div>
</td>
</tr>
</table>

Javascript

$('.device-name').on('blur', function(event) {
alert(event.target.defaultValue);
alert(event.target.textContent);
});

编辑找到绕过我的代码的方法我将数据值添加到我的 div 中并使用 getAttribute 获取我的数据HTML

<table class="data  table-bordered table table-striped" id="ui" method="POST">
<tr style="background-color:blue;color:white;">
<td width="25%">Device-imei</td>
<td>Device-Model</td>
<td>device-nickname</td>
</tr>
<tr>
<td>"111111"</td>
<td>"Model"</td>
<td>
<div class="device-name" contenteditable data-value="Name">"Name"</div>
</td>
</tr>
<tr>
<td>"11121341"</td>
<td>"asdf"</td>
<td>
<div class="device-name" contenteditable data-value="Name">"Name"</div>
</td>
</tr>
</table>

JavaScript

$('.device-name').on('blur', function(event){
alert(event.target.getAttribute('data-value'));
alert(event.target.textContent);
})

最佳答案

The target property can be the element that registered for the event or a descendant of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

source

所以在你的情况下它和你会做的一样

$('.device-name').on('blur', function(event) {
alert(this.defaultValue);
alert(this.textContent);
});

没有defaultValue这样的东西

解决方案

如果你想存储值,你可以将它分配给元素属性并使用 jQuery 函数 attr()data() 或 javascript 函数 检索它getAttribute()

$('.device-name').on('blur', function(event) {
alert(event.target.getAttribute('data-default'));
alert($(event.target).attr('data-default'));
alert($(event.target).data('default'));
alert(event.target.textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="data table-bordered table table-striped" id="ui" method="POST">
<tr style="background-color:blue;color:white;">
<td width="25%">Device-imei</td>
<td>Device-Model</td>
<td>device-nickname</td>
</tr>
<tr>
<td>"111111"</td>
<td>"Model"</td>
<td>
<div class="device-name" contenteditable data-default="Name">"Name"</div>
</td>
</tr>
<tr>
<td>"11121341"</td>
<td>"asdf"</td>
<td>
<div class="device-name" contenteditable data-default="Name">"Name"</div>
</td>
</tr>
</table>

关于javascript - 如何获取事件目标默认值 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50266732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com