问题描述:

I have a very simple HTML file (it's part of an MVC 4 project but i also tested on a plain HTML file)

that contains two buttons and some jquery script:

<html>

<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

</head>

<body>

<div>

<button id="btn1">Get a string</button>

<br />

<p id="p1" style="font-size: 12px" />

<br />

<button id="btn2">Get user agent</button>

<br />

<p id="p2" style="font-size: 12px" />

<br />

</div>

<script>

$(function () {

$('#btn1').click(function () {

$('#p1').text('clicked');

});

});

</script>

<script>

$(function () {

$('#btn2').click(function () {

$('#p2').text(navigator.userAgent);

});

});

</script>

</body>

after clicking the second button everything works great, but when clicking the first button (btn1) the second one disappears.

I tried switching them and changing the implementation of the script:

<script>

$(function () {

$('#btn1').click(function () {

$('#p1').text('clicked');

});

});

$(function () {

$('#btn2').click(function () {

$('#p2').text(navigator.userAgent);

});

});

</script>

and:

<script>

$(document).ready(function () {

$('#btn1').click(function () {

$('#p1').text('clicked');

});

});

$(document).ready(function () {

$('#btn2').click(function () {

$('#p2').text(navigator.userAgent);

});

});

</script>

but nothing change.

any ideas on how to solve it?

网友答案:

The problem is that you did not close your <p> tags properly. You did <p .... /> but it needs to be formatted like this <p ...></p>.

See: http://codepen.io/AlienHoboken/pen/kinGq

网友答案:

You have to use a closing </p> tag. A self-closing tag won't work:

<button id="btn1">Get a string</button>
<br />
<p id="p1" style="font-size: 12px"></p>  <-- here
<br />
<button id="btn2">Get user agent</button>
<br />
<p id="p2" style="font-size: 12px"></p> <-- and here
网友答案:

use this: http://jsbin.com/eqawas/1/edit

<div>
    <button id="btn1">Get a string</button>
    <br />
  <p id="p1" style="font-size: 12px"></p>
    <br />
    <button id="btn2">Get user agent</button>
    <br />
    <p id="p2" style="font-size: 12px" ></p>
</div>
网友答案:

default behaviour of "button" tag is submit. so you need to specify type="button" with like

<button id="btn1" type="button">Get a string</button>

and code onlod should be like

$(function () {
    $('#btn1').click(function () {
        $('#p1').text('clicked');
    });
    $('#btn2').click(function () {
        $('#p2').text(navigator.userAgent);
    });
});
相关阅读:
Top