从jquery中的多个元素中进行选择

selecting from multiple elements in jquery

本文关键字:行选 元素 选择 jquery      更新时间:2023-09-26

我正试图将此JavaScript代码更改为jQuery,但我不确定将onClick = 'function(this)'与jQuery的.click函数等同于什么。

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">
$('input[type="text"]').on('click', function(){
  $('#show_' + $(this).attr('name')).val($(this).val());
});

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

Fiddle:http://jsfiddle.net/gTtHT/1/

jQuery使用CSS选择器访问DOM中的元素。如果你给这些输入元素一个类名,比如"settable",你可以添加行为:
$(".settable").click(function(e){
    var getClicked = $(this).attr('name');
    ...
});

其中$(this)指的是已单击的元素。

如果DOM中已经存在输入,则以下操作将起作用。

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

否则,请尝试

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