jQuery/ajax按钮使用变量单击 [英] jQuery/ajax button click using variable
问题描述
我想使用jQuery/Ajax实现一个简单的网页. 我有3个按钮,每个按钮都将使用ajax调用从服务器获取不同的文件.唯一的区别是每个按钮都有不同的类名,并调用不同的文件.其他所有内容,例如加载时间,加载图标,成功/失败消息,都相同.因此,我只想编写1个ajax函数,而不是3个.
I want to implement a simple webpage using jQuery/Ajax. I have 3 buttons, each of which will use ajax call to get different files from the server. The only difference is that each button has different class name, and calls different files. Everything else, such as the loading time, loading icon, success/fail message, are all the same. Therefore, I would like to write only 1 ajax function, instead of 3.
我有:
<script>
$(document).ready(function(){
$(".button1").click(function(){
$.ajax({
url: "button1.txt",
/*more code*/
});
});
});
</script>
我想创建另一个函数,以便此"button1"和"button1.txt"成为变量,并且从该函数返回的任何内容都将用于ajax函数中,这样我就可以重用ajax函数3次. 你怎么能做到这一点?
I want to create another function so that this "button1" and "button1.txt" will become a variable, and whatever is returned from the function will be used in the ajax function, in which way I can reuse the ajax function 3 times. How could you achieve this?
推荐答案
您需要在所有三个按钮上设置url,例如
Your need to set url on all three button like
<button class='button1' data-url='button1.txt'>button 1</button>
<button class='button2' data-url='button2.txt'>button 2</button>
<button class='button3' data-url='button3.txt'>button 3</button>
在那之后,在您的ajax上.
After That on your ajax.
<script>
$(document).ready(function(){
$(".button1, .button2, .button3").click(function(){
var url = $(this).attr('data-url');
$.ajax({
url: url",
/*more code*/
});
});
});
这篇关于jQuery/ajax按钮使用变量单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!