简体   繁体   English

用WordPress编写JavaScript的正确方法是什么?

[英]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 . 我找到了我喜欢使用的JavaScript代码,但我需要将其写在我的WordPress网站上……这是一个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. 编辑:如果要使文本更大,则在JavaScript中添加span标签时,请向其中添加一个类。 See fiddle . 见小提琴


ORIGINAL ANSWER 原始答案

I'm not sure why JavaScript is being used here like this. 我不确定为什么在这里使用JavaScript。 In this example why not just wrap the numbers in span tags like so: 在此示例中,为什么不像这样将数字包装在span标签中:

<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. 然后使用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: 如果要使数字大于文本,则可以使用CSS设置跨度样式以具有更大的字体大小,或者也可以使用以下类:

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

And CSS: 和CSS:

span {
    color:blue
}

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

See fiddle 见小提琴

The first thing to note is that WordPress loads jQuery in "noconflict" mode. 首先要注意的是WordPress以“ noconflict”模式加载jQuery。 This means the $ shortcut isn't available. 这意味着$快捷方式不可用。 You need to reference the jQuery() function directly. 您需要直接引用jQuery()函数。 For example, jQuery('p') instead of $('p') . 例如,用jQuery('p')代替$('p')

Your theme may not be loading jQuery, so you'll need to call wp_enqueue_script('jquery'); 您的主题可能未加载jQuery,因此您需要调用wp_enqueue_script('jquery'); in your theme's functions.php file or a custom plugin. 在主题的functions.php文件或自定义插件中。

You don't say where you're putting these <script> tags. 您没有说要把这些<script>标记放在哪里。 By default, only Administrator users can put <script> in a post through the editor. 默认情况下,只有管理员用户可以通过编辑器将<script>放入帖子中。 This restriction is there for security reasons. 出于安全原因,存在此限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM