jQuery - On Mouse Over Change Text

2019-09-20 16:22发布

问题:

<span id="change">
    Stuff In Here
</span>

<script>
$("#change").on("mouseover", function () {
     $('#change').text("This is the new html");
});
</script>

The following doesn't work, as a jQuery noob, I'm not sure why.

回答1:

Change this:

<script>
 $("#change").on("mouseover", function () {
   $('#change').text("This is the new html");
 });
</script>

Because you are not referencing anything. Try this:

<script>
  $(document).ready(function () {
    $("#change").mouseover(function () {
      $('#change').text("This is the new html");
    });
  });
</script>

Well, there was another error in the fiddle. You had not selected any jQuery version in the upper left corner. After updating, the code worked perfectly, and from this I concluded that you might have not linked the script in your website.

Try linking the script file in the head section of your layout (website)

Here have a look now: http://jsfiddle.net/afzaal_ahmad_zeeshan/HMhVn/3/

I have updated it, and it runs perfectly now :)



回答2:

Here you go! http://jsfiddle.net/HMhVn/6/

If you want, for more flexibility, you can cache the original string to access later by putting the text in a variable before you decide what do to on mouseover.

HTML:

<span id="change">
    Stuff In Here
</span>

JQuery:

$(document).ready()
{
    $("#change").hover(
        function() // on mouseover
        {
            $(this).text("This is the new html");
        }, 

        function() // on mouseout
        {
            $(this).text("Stuff In Here");

        });
};

This allows you to change it permanently or not, it's up to do. Personally, I'd code it for flexibility.