[英]Jquery / Javascript - Uncaught TypeError: undefined is not a function
Google doesn`t execute my JS code. 谷歌没有执行我的JS代码。 In Firefox everything works fine 在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.text_1').text().contains("smth1") ) {
//smth here
}
Chrome console output points to "if" line above. Chrome控制台输出指向上方的“if”行。
Uncaught TypeError: undefined is not a function (anonymous function) f.event.dispatch jquery-1.7.2.min.js:3 h.handle.i 未捕获的TypeError:undefined不是函数(匿名函数)f.event.dispatch jquery-1.7.2.min.js:3 h.handle.i
How to fix this? 如何解决这个问题? Nothing goes at mind now, name function and compare it with bool before if ? 现在没有什么可以记住,命名功能并在之前与bool进行比较?
Use something like this: 使用这样的东西:
if ( $('div.text_1').text().indexOf("smth1") !== -1 ) {
//smth here
}
The indexOf
will return something other than -1 if "smth1" exists somewhere in your text. 如果文本中某处存在“smth1”, indexOf
将返回-1以外的值。
You can't call .contains() on the text value returned from .text(). 您不能对.text()返回的文本值调用.contains()。
If you test the value after extracting it with jQuery you should be ok. 如果在使用jQuery解压缩后测试该值,那么应该没问题。
var divText = $('div.text_1').text();
if(divText.indexOf("smth1") != -1){
//do your stuff...
}
Why don't you just use the same check you used when choosing which text to append: 为什么不在选择要追加的文本时使用相同的检查:
if ( $('div.text_1').text() === "smth1" ) {
// do it
}
Also another way to do it with a single class 另一种方法是使用单个类来完成它
<a href="#pricends">CLICK</a>
<div class="smth">smth1</div>
<div class="smth">smth2</div>
jQ: JQ:
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';
});
});
Somewhat extended: 有点扩展:
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';
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.