#wordpress 中JQuery使用问题 报错:Uncaught TypeError: $ is not a functionwordpress问题记录

Posted jaycethanks

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#wordpress 中JQuery使用问题 报错:Uncaught TypeError: $ is not a functionwordpress问题记录相关的知识,希望对你有一定的参考价值。

在企图通过css隐藏掉wordpress个人资料中的first-name 和 last-name时候,
在这里找到了相关的参考代码:
https://noexceptions.io/disabling-first-and-last-name-changes-in-the-wordpress-profile/

// Function to disable the first name and last name fields
function disable_first_and_last_name_fields() {
	?>
	<script type="text/javascript">
        $(function() {
            // Disable the first and last names in the admin profile so that user‘s cannot edit these
				$(‘#first_name‘).prop( ‘disabled‘, true );
				$(‘#last_name‘).prop( ‘disabled‘, true );
        });
   	</script>
	<?php
}

// Action hook to inject the generated JavaScript into admin pages
add_action( ‘admin_head‘, ‘disable_first_and_last_name_fields‘ );

比较简单,就是通过wordpress提供的action钩子,在内容管理页面注入jQuery脚本,把相关dom节点移除。

但是,直接在function.php中贴入的时候,发现并不起作用。

通过alert和console调试,发现代码块并未执行。

// Function to disable the first name and last name fields
function disable_first_and_last_name_fields() {
	?>
	<script type="text/javascript">
        $(function() {
			console.log("smt to be console");
			alert("alert smt");
            // Disable the first and last names in the admin profile so that user‘s cannot edit these
			$(‘#first_name‘).prop( ‘display‘, false );
			$(‘#last_name‘).prop( ‘disabled‘, true );
        });
   	</script>
	<?php
}

// Action hook to inject the generated JavaScript into admin pages
add_action( ‘admin_head‘, ‘disable_first_and_last_name_fields‘ );
            

最后在stackoverflow上找到了该问题的原因:

https://stackoverflow.com/a/45346975/12261182

就是把代码段中的$换作jQuery即可。

var $ = jQuery;

// Function to disable the first name and last name fields
function disable_first_and_last_name_fields() {
	?>
	<script type="text/javascript">
		let $ = jQuery;
        $(function() {
			console.log("smt to be console");
			alert("alert smt");
            // Disable the first and last names in the admin profile so that user‘s cannot edit these
			$(‘#first_name‘).prop( ‘display‘, false );
			$(‘#last_name‘).prop( ‘disabled‘, true );
        });
   	</script>
	<?php
}

// Action hook to inject the generated JavaScript into admin pages
add_action( ‘admin_head‘, ‘disable_first_and_last_name_fields‘ );
            

It works !

这个问题在这里有更加详细的讨论:https://stackoverflow.com/questions/12258282/typeerror-is-not-a-function-wordpress

https://stackoverflow.com/a/12258427/12261182



以上是关于#wordpress 中JQuery使用问题 报错:Uncaught TypeError: $ is not a functionwordpress问题记录的主要内容,如果未能解决你的问题,请参考以下文章

常见问题6:控制台报错整理——报错

用JQuery Validate框架,在IE8下验证报错问题解决

webpack安装jQuery报错

Eclipse项目中加入jquery.js文件报错(missing semicolon)问题

关于jquery $.browser 报错问题

关于Eclipse项目中加入jquery-1.x.js文件报错问题