2013-02-16 44 views
0

我正在尝试将此JavaScript代码更改为jQuery,但我不确定相当于使用onClick = 'function(this)'与jQuery的.click函数。从jquery中的多个元素中进行选择

的JavaScript:

function setInput(text) { 

    var getClicked = text.name; 
    var click = document.getElementById(getClicked); 
    var show = document.getElementById('show_' + getClicked); 

    show.value = click.value; 
} 

HTML:

<input type='text' name = "a" id = "a" onclick='setInput(this);'> 
<input type = "text" id = "show_a"><br> 
<input type='text' name = "b" id = "b" onclick='setInput(this);'> 
<input type = "text" id = "show_b"> 
+3

如果您不知道如何编写jQuery,那么您需要*学习* jQuery。 http://docs.jquery.com/Tutorials ... http://api.jquery.com/ – 2013-02-16 21:10:08

+0

显示你的尝试。你的问题是什么?您是否阅读过文档? http://api.jquery.com/click/ – 2013-02-16 21:10:43

+0

为什么你会使用jQuery,如果你已经有工作的香草JavaScript代码? – 2013-02-16 21:14:49

回答

1
$('input[type="text"]').on('click', function(){ 
    $('#show_' + $(this).attr('name')).val($(this).val()); 
}); 
+0

谢谢你的工作很好,只是我正在寻找 – user2014429 2013-02-16 21:20:54

1

如果DOM已经存在的输入,下面的工作。

$('#a, #b').click(function() { 
    setInput(this); 
}); 

否则,请尝试

$(function() { 
    $('#a, #b').click(function() { 
     setInput(this); 
    }); 
}); 
+0

谢谢你的职位 – user2014429 2013-02-16 21:28:04

1

HTML:

<input class="clickme" type="text" name ="a" id ="a"> 
    <input type ="text" id ="show_a"><br> 
<input class="clickme" type="text" name ="b" id ="b"> 
    <input type ="text" id ="show_b"> 

的jQuery:

$(document).ready(function(){ 
    $(".clickme").click(function(){ 
     id = "#show_"; 
     id += $(this).prop("id"); 
     $(id).show(); 
    }); 
}); 

小提琴:http://jsfiddle.net/gTtHT/1/

+0

谢谢你的帖子和jsfiddle链接 – user2014429 2013-02-16 21:28:27

1

jQuery使用CSS选择器来访问DOM中的元素。如果你给这些输入要素类名称,如“可设置”,你可以添加行为:

$(".settable").click(function(e){ 
    var getClicked = $(this).attr('name'); 
    ... 
}); 

其中$(这)是指已经被点击的元素。

+0

谢谢你的帖子 – user2014429 2013-02-16 21:29:32