简体   繁体   中英

Alter the text in the p tags

I want to alter the text in the p tags to gain (upon clicking the text) the properties set by the attribution class.

Here is the HTML:

<p onclick="function">Hello</p>

CSS:

.attribution{
color:blue;
font-weight:bold;
}

Javascript:

var main = function() {
$('<p>').text('.attribution');
};
$(document).ready(main);

Thank You!

<p onclick="function">Hello</p>

You:

  1. Have to use the name of the function, not the keyword function which creates a new function.
  2. Have to actually call the function, by appending () to the variable name
  3. Shouldn't use intrinsic event attributes at all. Bind event handlers with JavaScript.

So

<p>Hello</p>

<script>
    $("p").on("click", main);
</script>
 var main = function() { $('<p>').text('.attribution'); }; $(document).ready(main);

You:

  1. Should use a function declaration (since it plays nicely with debuggers)
  2. Need to select the existing paragraph instead of creating (and promptly discarding) a new one)
  3. Add attribution to the classes on the element instead of replacing the text content of it with the phrase ".attribution"
  4. Not call the function on DOM ready when you want it to be called when something is clicked

Such

function main() {
   $('p').addClass('attribution');
};

As an aside, paragraphs are not designed to be interactive. While you can click on them with a mouse pointer, nothing encourages people to do so, they are outside the normal focus list (so people who don't use a mouse can't tab to them) and don't show up in screen readers as something that should be clicked on. Use appropriate markup (perhaps a button).

Okay, since your loading JQuery why no use its methods for handling click events and changing the css properties.

 $( "p" ).on( "click", function() { $(this).addClass('attribution'); });

1) You are not actually hooking any callback function to onclick event. You need to specifiy what function you want to be executed on click. So: HTML:

<p onclick="addClass(event)">Hello</p>

JavaScript:

function addClass(evt){
        evt.target.classList.add('attribution');
    }

jQuery alternative:

var main = function(){
    $("p").click(function(){
        $(this).addClass("attribution");
    });
}
$(document).ready(function(){
    main();
});

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