简体   繁体   中英

Jquery Click Function-get value of clicked tag

<?php
include 'dbc.php';
?>
<?php
$query  =   mysql_query("SELECT * FROM `editor`");
 $row=mysql_fetch_row($query);
?>

<script type="text/javascript" src="assets/js/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.js"></script>
<link type="text/css"  rel="stylesheet" href="assets/css/bootstrap.css" />

<script type="text/javascript">
    $(document).ready(function(){
        $("#text").click(function(){
        var alrt =  $(this).text();
        alert(alrt);
        })  ;
    
    
    });//ready function end here
</script>
<span id="text">
<?php echo $row['0']; ?>
</span>
<br />
<br />
<span id="text">
<?php echo $row['1']; ?>
</span>
<br />
<br />
<span id="text">
<?php echo $row['2']; ?>
</span>

This is one of my sample page and the script, but its not working properly, I'm getting the value of 1st span when its clicked, not the rest, now the question is, I want to get the value of clicked span, without knowing its id or class. Please help.

Just select the span using jquery selector like this :

$('span').click(...

Here is your example :

<script type="text/javascript">
$(document).ready(function(){
    $("span").click(function(){
    var alrt =  $(this).text();
    alert(alrt);
    })  ;
});//ready function end here
</script>

id must be unique. You should use class .

<span class="text">
<?php echo $row['0']; ?>
</span>
<br />
<br />
<span class="text">
<?php echo $row['1']; ?>
</span>

For the javascript, use $(".text").click instead of #text to point to the elements of that class.

In your HTML replace id = "text" with class="text" . Then your jquery would look like this:

$(document).ready(function(){
    $(".text").click(function(){
        alert($(this).text());
    });
});

Don't use the same ID for more than 1 element in an HTML page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM