开发者

Simpler DIV/JavaScript update?

This is a newbie question: Can the following HTML/JavaScript code be further simplified by just keeping the DIV to be updated + the INPUT button?

<div id="main_section" name="main_section">
    <div id="update_div">Old stuff</div>
    <input type="button" value="Update" id="update_button"/>
</div>

<script type="text/javascript" src=开发者_如何学Go"/jquery.js"></script>

<script type='text/javascript'>
    $("#update_button").click(function() {
        $("#update_div").html("New stuff");
    })
</script>

Thank you.


You can even inline JavaScript code in your HTML but that is a horrible practice unless you know exactly what you're doing. Reads as:

<div id="update_div">Old stuff</div>
<input type="button" value="Update" onclick="$('#update_div').html('...')" />

If you want to encode the knowledge of what gets updated with that on click, then you can encode that knowledge in the HTML elements itself.

<div id='target'>Old</div>
<input type='button' value='Update' data-target='#target' date-value='New' />

In jQuery's onload, define this for all such buttons:

Since the data seems to be static here, a better global approach might be to define the data on the elements itself, and setup all handlers in one global sweep of the DOM.

$(function() {
    $(':button').click(function() {
        var dest = $(this).attr('data-target');
        var value = $(this).attr('data-value');
        $(dest).html(value);
    });
});

The above code still requires external JavaScript but only need it once for all such button and div elements on the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜