2013-02-16 42 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