jQuery针对同一元素的多个按钮 [英] jQuery multiple buttons targeting the same element

查看:88
本文介绍了jQuery针对同一元素的多个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行的操作是将div作为目标,并根据按钮的单击将其填充为文本.假设有三个按钮,用户单击第一个按钮,文本将填充在下面的文本框中.

这是我的脚本代码:

<script type="text/javascript">
$(document).ready(function (){
$('#button1').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 1');
});
});
</script>

这是到目前为止我所拥有的: http://jsfiddle.net/nzTwU/

这是我在此站点上的第一个问题,因此,如果有任何不正确之处,我深表歉意.我之前也从未使用过jsfiddle,所以我希望这也是正确的.如果不是,就让我知道.

现在第一个按钮可以正常工作,我已经将它先清空了div,因此,如果您多次单击该按钮,则不会一遍又一遍地输入相同的文本.如何为其他按钮编写相同的脚本?我是否使用if语句?有什么更好或更合适的方法可以解决我的问题吗?还是我想做的事可能吗?我对jQuery有非常初级的知识,但不确定如何去做.

感谢所有建议!

解决方案

(document).ready(function (){
$('#button1').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 1');
});
  $('#button2').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 2');
});
     $('#button3').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 3');
});
});

这是我编辑过的jsfidle

http://jsfiddle.net/nzTwU/3/

What I'm looking to do is target a div and populate it with text depending on a button click. There would be say, three buttons, the user clicks the first button, text is populated in the text box below.

Here's my script code:

<script type="text/javascript">
$(document).ready(function (){
$('#button1').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 1');
});
});
</script>

Here's what I have so far all together: http://jsfiddle.net/nzTwU/

This is my first question on this site, so if anything is not right, my apologies. I've also never used jsfiddle before so I hope that's right too. If not just let me know.

Right now the first button works fine, I've got it emptying the div first so if you click the button multiple times it doesn't input the same text over and over again. How do I script the same for the other buttons? Do I use an if statement? Is there a better or more appropriate method for what I'm trying to do? Or is what I want to do even possible? I have an extremely rudimentary knowledge of jQuery and I'm unsure how to go about this.

Thanks for any and all advice!

解决方案

(document).ready(function (){
$('#button1').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 1');
});
  $('#button2').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 2');
});
     $('#button3').click(function (){
            $('#textbox').empty();
    $('#textbox').prepend('Some text from Button 3');
});
});

here is jsfidle i have edited

http://jsfiddle.net/nzTwU/3/

这篇关于jQuery针对同一元素的多个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆