简体   繁体   English

jQuery选择器,我的代码有什么问题?

[英]jquery selectors, what is wrong with my code?

What i want to do is that when i click on the button "1" it should display the number "1" in the textbox above it. 我想做的是,当我单击按钮“ 1”时,它上方的文本框中应显示数字“ 1”。

what is wrong with my jquery code? 我的jquery代码有什么问题?

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JQuery Tutorial</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
    <input id="textbox" type="text" />

    <div>
        <input id="1" type="button" value="1" />
        <input id="2" type="button" value="2" />
        <input id="3" type="button" value="3" />
    </div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
    <script type="text/javascript" src="js/ext.js"></script>
</body>

My jquery 我的jQuery

$('#1').click(function)({
  var txt = $('#textbox');
  $('#1').html('txt');
});

Try this code 试试这个代码

 $('input[type="button"]').click(function() {    
       var txt = $(this).val();
       $('#textbox').val(txt);    
 });

Will explain your problem with your jQuery code: 将用您的jQuery代码解释您的问题:

Line 1: You registered with #1 button so this will be triggered on when button 1 is click, I made it generalised 第1行:您注册了#1按钮,因此单击按钮1时就会触发此操作,我对此做了概括

Line 2: You are getting value from textbox, whereas you are supposed to take value from button text. 第2行:您正在从文本框中获取价值,而您应该从按钮文本中获取价值。

Line 3: You are assigning value in button, whereas you are supposed to assign to textbox and always use val() for input type of control and html() for other html container controls 第3行:您在按钮中分配值,而您应该分配给文本框,并且始终将val()用于控件的输入类型,并将html()用于其他html容器控件

The above were your errors explained. 以上是您解释的错误。

Queries welcomed! 欢迎查询!

Fiddle demo 小提琴演示

$(function(){
 $('input[type="button"]').click(function(){
  $('#textbox').val($(this).val());

 });
});

You have to get the value using val() method. 您必须使用val()方法获取值。 Also, you are passing variable txt as string to the html() function which is wrong. 另外,您将变量txt作为字符串传递给html()函数,这是错误的。 Try the below... 请尝试以下...

var txt = $('#textbox').val();

$('#input1').html(txt);

Try this 尝试这个

 $('input[type="button"]').click(function() {
   $('#textbox').val($(this).val());
 });

You can try this one 你可以试试这个

$('div').on('click', 'input', function () {
    $('#textbox').val(this.value);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM