简体   繁体   中英

How to get value from particular element?

I need to take value, when click on particular link which has id="username" but it does not work...

My attempt:

function rev() {
    var username = (this).getElementById("username").textContent;
    return alert (username);
}
while($trackResultRow = mysqli_fetch_assoc($trackResult)){?>

    <a onclick="rev()"><span class="glyphicon glyphicon-thumbs-down pull-right"></span></a>
    <span class="glyphicon glyphicon-thumbs-up pull-right"></span>
    <li>
        <a href="<?php echo $trackResultRow['track_path']?>"><span id="username"><?php echo $trackResultRow['username']?></span> - <span id="track"><?php echo $trackResultRow['track_name']?></span>

            <span class="glyphicon glyphicon-download pull-right"></span>
            <div class="pull-right">
                <span class="glyphicon glyphicon-pause pull-right" onclick="document.getElementById('aud').pause()"></span>
                <span class="glyphicon glyphicon-play pull-right" onclick="document.getElementById('aud').play()"></span>
            </div>
        </a>
    </li>
    <hr>
<?php
    }
?>

Also I tryed

function rev() {
   var username = document.getElementById(value).textContent;

   return alert (username);
}


 <button id="but" onclick="rev()">hey</button>
 <button id="but" onclick="rev()">hey233</button>

Any ideas?

如果要定位页面上的元素,请使用document.getElementById

document.getElementById("username").textContent;

Use this for taking value from a html.

var value = document.getElementById('id').value;

If you want to get a specific value stored in a variable that is in your PHP code.

<input type = "text" id = "id" name = "var_PHP" value = "<?php echo $var_php;?>">

There are two things you can do,

1) Assign different ID to the each element found by $trackResultRow['username'] by adding an incrementing variable like username_1, username_2 and then getElementById for each ID putting that in a for loop.

2) Assign a Class instead of ID and getElementsByClass and iterate through the result and get the value by using this how to get value by class name using javascript

getElementsById() will only give you first element.

id in attribute tag html must different. Try this

 <!DOCTYPE html> <html> <body> <button id="items" onclick="myFunction(this.id)">Try it</button> <button id="item" onclick="myFunction(this.id)">Try it again</button> <p id="demo"></p> <script> function myFunction(id) { var x = document.getElementById(id).textContent; document.getElementById("demo").innerHTML = x; } </script> </body> </html> 

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