javascript从按钮运行动态代码

时间:2018-05-15 23:10:08

标签: javascript jquery json

这是html代码 测试

我是新手并在js文件中运行此代码并且它可以正常工作。唯一的问题是我的JQUERY网站上的所有按钮。任何人都可以帮助我,告诉我如何让它专门针对一个......

$(document).ready(function(){
    $("button").click(function(){
        $.getJSON("js/jobs.json", function(result){
           $.each(result, function(i, field){
                $("div").append(field + " ");
                            });
        });
    });
});

4 个答案:

答案 0 :(得分:0)

最简单的方法是将id属性添加到要定位的特定按钮。然后你就可以像这样添加点击事件:

$('#buttonId').click(...)

答案 1 :(得分:0)

您必须先学习HTML。在这种情况下,您需要为此元素分配ID ATTRIBUTE,例如

<button id ='myButton'>Test</button>

单击该按钮后,此代码将起作用。但是你需要定位那个确切的按钮,见下文

$(document).ready(function(){
    $("#myButton").click(function(){
        $.getJSON("js/jobs.json", function(result){
           $.each(result, function(i, field){
                $("div").append(field + " ");
                            });
        });
    });
});

您也没有发布可能有助于撰写此答案的HTML代码。您的JS代码(JQ)会将此json结果附加到页面上的所有DIVS,因为您的选择器(div)。

答案 2 :(得分:0)

始终使用类作为选择器。

在HTML中添加一个类。

<button class='js-test-button'>Test</button>

然后更新JS代码。

$(".js-test-button").click(function(){
        $.getJSON("js/jobs.json", function(result){
           $.each(result, function(i, field){
                $("div").append(field + " ");
                            });
        });
    });

答案 3 :(得分:0)

试试这个:

&#13;
&#13;
$(document).ready(function(){
    $("#mybutton").click(function() {
        // your code comes here
        console.log("My button click");
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="mybutton" value="Submit"/>
&#13;
&#13;
&#13;