简体   繁体   中英

I'm trying to create a dynamic HTML update using a button

I'm very new to Javascript and this is my first time creating my own function. I'm trying to change the color of links based on whether or not the user clicks a button I've created. The code is as follows:

<p align="center">
    <input type="button";
           onclick="changelinks"
           value = "Click this if you can't see the links!"/>
</p>

This is the code I have for my function.

<script type="text/javascript">
              function changelinks(links) {
                var element = document.getElementByClass("links");
                element.onclick.color = "#00FF7F";
                 }
                 </script>

Do you have any suggestions to make my function work? How can I link my function to the button? Thanks in advance, I really appreciate it.

Among others, these are some major issues:

1.There is no getElementByClass - there is getElementsByClassName or getElementById

2. element.onclick.color = "#00FF7F"; is wrong.

3. type="button"; onclick="changelinks" type="button"; onclick="changelinks" should not have a ; and changelinks needs ()

Try this:

<script type="text/javascript">
    function changelinks() {
        var element = document.getElementById("links");
            element.style.color = "#000";
    }
 </script>


<a href="#" id="links" style="color:#fff">Hello</a>

<p align="center">
    <input type="button" onclick="changelinks()" value = "Click this if you can't see the links!"/>
</p>

This is a simple example that will do what you one for one link id="links" . To do something similar with multiple elements of the same class, see this question and the javascript manual .

Also, note that this example uses pure javascript, but a cleaner and simpler solution could be had using JQuery - see Johannes N's answer for details.

This can be easily done using jQuery.

Html:

<p id="button">Button</p>
<a href="" class="links">link</a>

JavaScript:

$(function() {
    $('#button').click(function() {
        $('.links').css("color", "red");
    });
});

Working example: http://jsfiddle.net/YS79d/

addClass and removeClass in jquery does the trick

HTML/CSS

<style>
.links {
color:#FF0000;
}
.links2 {
color:#0000FF;
}
</style>
<p id="button">Button</p>
<a href="" class="links">link</a>

Javascript

$('#button').toggle(function () {
    $(".links").addClass("links2");
}, function () {
    $(".links").removeClass("links2");
});

Working JSFiddle example

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