简体   繁体   中英

What is the right way to write JavaScript in WordPress?

I found JavaScript code I like to use, but I need it to be written in my WordPress website ... Here is a JSFiddle .

Here is how I tried to write it:

 <head> <style> p span {color:blue;} </style> </head> <body> <p>sony sensor 2.1mp</p> <script> $('p').html(function(index, value) { return value.replace(/(\\d+)/g, '<span>$1</span>'); }); </script> </body> 

What do I need to change in the script to make it work?

EDIT: If you want to make the text bigger, when you're adding the span tags in the JavaScript add a class to them. See fiddle .


ORIGINAL ANSWER

I'm not sure why JavaScript is being used here like this. In this example why not just wrap the numbers in span tags like so:

<p>Text and numbers: <span>123</span></p>
<p><span>123</span> and text</p>

And then add the styles to the spans appropriately with the CSS. If you are wanting to make the numbers larger than the text just style the spans with the CSS to have larger font size, or also use classes such as:

<p>Text and numbers: <span class="big">123</span></p>
<p><span class="big">123</span> and text</p>

And CSS:

span {
    color:blue
}

span.big {
  font-size: 3em;
}

See fiddle

The first thing to note is that WordPress loads jQuery in "noconflict" mode. This means the $ shortcut isn't available. You need to reference the jQuery() function directly. For example, jQuery('p') instead of $('p') .

Your theme may not be loading jQuery, so you'll need to call wp_enqueue_script('jquery'); in your theme's functions.php file or a custom plugin.

You don't say where you're putting these <script> tags. By default, only Administrator users can put <script> in a post through the editor. This restriction is there for security reasons.

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