[英]jquery.click(function) wordpress widget
當我在標題中使用此函數時,它可以正常工作,但是當我在小部件中使用它時,什么也沒發生
$("#myID").click(function(){
var name = $("#name").val();
var phone = $("#phone").val();
console.log(name +" "+ phone);
if(name.length > 1 && phone.length > 7){
$.ajax({
url: 'my_url',
type: 'post',
data: {'name': name,
'number': phone},
success: function(data){
$(".header-bg-title").html('thanks');
$("span.white").hide();
},
error: function(response){
alert('error');
}
});
} else {
$("p#onerror").html('write your name & number');
}
});
HTML
<div class="col-xs-12">
<h2>text</h2>
<p id="onerror">My text</p>
<p><input id="name" class="form-control" type="text" placeholder="Name" /></p>
<p><input id="phone" class="form-control" type="text" placeholder="Phone" /></p>
<p><button id="myID" class="btn btn-warning btn-block btn-lg" type="button">Send</button></p>
</div>
任何有建議的人嗎?
據我所知,.click將在執行時附加到該項目,如果該項目不存在,則在小部件的情況下將不會附加。 我對此可能是錯的,請嘗試一下並查看是否可行。
$('body').on('click', '#myID', function() {
...
});
嘗試使用jQuery函數,而不是$。
您的代碼是這樣的:
jQuery("#myID").click(function(){
var name = jQuery("#name").val();
var phone = jQuery("#phone").val();
console.log(name +" "+ phone);
if(name.length > 1 && phone.length > 7){
jQuery.ajax({
url: 'my_url',
type: 'post',
data: {'name': name,
'number': phone},
success: function(data){
jQuery(".header-bg-title").html('thanks');
jQuery("span.white").hide();
},
error: function(response){
alert('error');
}
});
} else {
jQuery("p#onerror").html('write your name & number');
}
});
或者,您也可以將代碼包裝在IIFE中,以美元接收jQuery
(function($) {
// your code here
}(jQuery));
我猜你目前有這樣的功能
$(document)ready(function(){
$("#myID").click(function(){
var name = $("#name").val();
var phone = $("#phone").val();
console.log(name +" "+ phone);
if(name.length > 1 && phone.length > 7){
$.ajax({
url: 'my_url',
type: 'post',
data: {'name': name,
'number': phone},
success: function(data){
$(".header-bg-title").html('thanks');
$("span.white").hide();
},
error: function(response){
alert('error');
}
});
} else {
$("p#onerror").html('write your name & number');
}
});
}
如果是這樣,那應該就像將$(document)ready(function(){更改為jQuery(document).ready(function($))並保持其余部分一樣簡單。
jQuery(document).ready(function($)
{
$("#myID").click(function(){
var name = $("#name").val();
var phone = $("#phone").val();
console.log(name +" "+ phone);
if(name.length > 1 && phone.length > 7){
$.ajax({
url: 'my_url',
type: 'post',
data: {'name': name,
'number': phone},
success: function(data){
$(".header-bg-title").html('thanks');
$("span.white").hide();
},
error: function(response){
alert('error');
}
});
} else {
$("p#onerror").html('write your name & number');
}
});
}
該解決方案使您可以繼續使用$('#idofitem')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.