Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-按钮_Javascript_Jquery - Fatal编程技术网

Javascript jQuery-按钮

Javascript jQuery-按钮,javascript,jquery,Javascript,Jquery,我有个问题,我写了一个jQuery脚本 $.ajax({ type: "GET", url: "/api/template", processData: true, dataType: 'text', cache: false, success: function (data, textStatus, request) { template = jQuery.parseJSON(data); if (template

我有个问题,我写了一个jQuery脚本

$.ajax({
    type: "GET",
    url: "/api/template",
    processData: true,
    dataType: 'text',
    cache: false,
    success: function (data, textStatus, request) {
        template = jQuery.parseJSON(data);
        if (template.templateCur == 1) {
            $("button[id='T1']").css("color", "red");
        } else {
            $("button[id='T1']").css("color", "black");
        }
        if (template.templateCur == 2) {
            $("button[id='T2']").css("color", "red");
        } else {
            $("button[id='T2']").css("color", "black");
        }
        if (template.templateCur == 3) {
            $("button[id='T3']").css("color", "red");
        } else {
            $("button[id='T3']").css("color", "black");
        }
    }
});
我有3个按钮,如果你加载网站,脚本将加载,并显示设备上哪个模板是活动的-JSON说它


所以我有3个不同的按钮。脚本首先通过JSON检查我设备上的三个模板中的哪一个是活动的,并用红色标记按钮。当我按下另一个按钮时,设备将更改我的模板,但该按钮未标记为红色。这就是问题所在,如何使脚本在单击按钮时始终执行new。接下来我将有更多的按钮,我不希望代码太长。

HTML

<button class="myButton" id="T1">My Button</button>
<button class="myButton" id="T2">My Button</button>
<button class="myButton" id="T3">My Button</button>

在获取JSON时,为什么要将数据类型设置为text?另外,你在这里要求什么也不清楚?你能不能给你期望发生的事情增加一些细节。你问题的重点不清楚,所以我有3个不同的按钮。脚本首先通过JSON检查我设备上的三个模板中的哪一个是活动的,并用红色标记按钮。当我按下另一个按钮时,设备将更改我的模板,但该按钮未标记为红色。这就是问题所在,如何使脚本在单击按钮时始终执行new。接下来我会有更多的按钮,我不希望代码太长。
$('.myButton').on('click', function () { //Event Handler for your button
    myRequest(); //Call the request function
});

function myRequest() {
    $.ajax({
        type: "GET",
        url: "/api/template",
        dataType: 'json',
        success: function (template) {
            $('.myButton').css("color", "black"); //Reset all buttons with class "myButton"
            $("#T" + template.templateCur).css("color", "red"); //Set color for active Template-Button
        }
    });
}


(function(){
    myRequest();
})();