Jquery/Javascript-未捕获类型错误:未定义不是函数
谷歌不会执行我的JS代码。在Firefox中,一切正常Jquery/Javascript-未捕获类型错误:未定义不是函数,javascript,jquery,Javascript,Jquery,谷歌不会执行我的JS代码。在Firefox中,一切正常 $('a[href="#pricends"]').click(function(){ $("div.text_1").text(($("div.text_1").text() == 'smth1') ? 'smth2' : 'smth1') $("div.text_2").text(($("div.text_2").text() == 'smth2') ? 'smth1' : 'smth2') if ( $('div.te
$('a[href="#pricends"]').click(function(){
$("div.text_1").text(($("div.text_1").text() == 'smth1') ? 'smth2' : 'smth1')
$("div.text_2").text(($("div.text_2").text() == 'smth2') ? 'smth1' : 'smth2')
if ( $('div.text_1').text().contains("smth1") ) {
//smth here
}
Chrome控制台输出指向上面的“如果”行
未捕获类型错误:未定义不是函数
(匿名函数)
f、 event.dispatch jquery-1.7.2.min.js:3
h、 处理,我
如何解决这个问题?现在想都不想了,命名函数并将其与之前的bool进行比较,如果?使用类似的方法:
if ( $('div.text_1').text().indexOf("smth1") !== -1 ) {
//smth here
}
如果文本中某处存在“smth1”,则索引of
将返回非-1的内容。无法对从.text()返回的文本值调用.contains()
如果在使用jQuery提取值后测试该值,则应该可以
var divText = $('div.text_1').text();
if(divText.indexOf("smth1") != -1){
//do your stuff...
}
为什么不使用选择要附加的文本时使用的相同检查:
if ( $('div.text_1').text() === "smth1" ) {
// do it
}
还有另一种使用单个类的方法 稍微扩展:
var $smth = $(".smth"); // Cache your elements
$('a[href="#pricends"]').click(function( e ){
e.preventDefault();
$smth.text(function(i, txt){
if(txt==="smth1"){
// do something with $(this)
// or do something else
}
// and afterwards thange text
return txt=='smth1'?'smth2':'smth1';
});
});
我只是在这里猜测,但是.text()是否只是返回一个字符串,因此无法在其上链接.contains()方法?JavaScript中的字符串没有
.contains()
方法,尽管它在ECMAScript 6中出现,并且目前在Firefox中可用。Chrome将其标记为实验性功能。很好的评论“饼干怪物”,谢谢。也要感谢大家,这是我的第一个问题,我真诚地说,在看到diff StackO的回复之前,我找到了答案answer@RokoC.Buljan我不知道IE8评论是关于什么的?indexOf在ie8Ah中不存在,它位于数组上,而不是字符串——这很好用。为了澄清.indexOf()
适用于字符串上的所有IE版本,但在IE8及以下版本中,数组对象不支持.indexOf()
方法。@scunliffe+1我的坏消息一定是在深夜+这是我第一个回答的答案。这是我要补充的答案+1.
var $smth = $(".smth"); // Cache your elements
$('a[href="#pricends"]').click(function( e ){
e.preventDefault(); // Prevent Browser default anchor behavior
$smth.text(function(i, txt){
return txt=='smth1'?'smth2':'smth1';
});
});
var $smth = $(".smth"); // Cache your elements
$('a[href="#pricends"]').click(function( e ){
e.preventDefault();
$smth.text(function(i, txt){
if(txt==="smth1"){
// do something with $(this)
// or do something else
}
// and afterwards thange text
return txt=='smth1'?'smth2':'smth1';
});
});