如何获得JavaScript函数中html输入框的“id”以将值设置为相应的输入框,该输入框调用JavaScript函数
<html>
<script type='text/javascript' src='./javasc.js'></script>
<input type='text' id='one' onclick='setVal()'/>
<input type='text' id='two' onclick='setVal()'/>
</html>javasc.js
function setVal()
{
$('#one').val("First Message");
$('#two').val("Second Message");
}我想要这样的东西。
javasc.js
function setVal()
{
id=getElementIdWhichInvokedTheFunction();
$(id).val("Some Message");
}发布于 2014-03-12 17:04:17
使用this引用:
function setVal(elem) {
id = elem.id;
$(id).val("Some Message");
}援引:
setVal(this);更新
如果传递对象,则不需要ID来操作它:
function setVal(elem) {
$(elem).val("Some message");
}您仍然使用setVal(this);调用
发布于 2014-03-12 17:26:22
如果你想像在你的帖子中那样使用你的功能
<input type='text' id='one' onclick='setVal()'/>您需要将其更改为
<input type='text' id='one' onclick='setVal(this);' />并修改函数以接受参数。
或
<input type='text' id='one' />
<input type='text' id='two' />
$("input").click(function(){
alert($(this).attr('id'));
});发布于 2014-03-12 17:03:48
您可以传递this(当前元素),该元素正在被单击,并从setVal()中的该元素获取id,如下所示
function setVal(elem){
id=elem.id; // id is 'one' if you click on button one
//do action with fetched id
}https://stackoverflow.com/questions/22358732
复制相似问题