开发者

jquery toggle() not working with variable

I wan't to be able to "toggle" a div using jquery through a function but it gives me

"Uncaught TypeError: Cannot read property 'defaultView' of undefined"

in the chrome debugger. here is my code

function hide(id){
$(id).toggle();
}

I have also tried

if (document.getElementById(id).style.display=="none"){
    document.getElementById(id).style.display="block";
}
else if (document.getElementById(id).style.display=="block"){
    document.getElementById(id).style.display="none";
}
console.log(document.getElementById(id));
console.log(id);
return document.getElementById(id).style.display;

and I get an error that says

"Uncaught TypeError: Cannot read property 'style' of null"

More info:

I call hide() from the HTML, I input the HTML using js

here is the basic code

function inputHtml(id){
 var div = document.createElement("div");
 div.innerHTML = '<div id="'+id+'"><div onclick="hide('+id+')">hide</div></div>'开发者_C百科;
 main.appendChild(div);
}


You are trying to toggle an id that doesn't exist.

But I guess the console.log(document.getElementById(id)); would show that already.


Sure the ID exists?

By the way, your function is selecting by tag name, not by ID:

function hide(id){
  $('#' + id).toggle();
}


First, your code should look like this:

function hide(id){
  $("#"+id).toggle();
}

Or this:

function hide(id){
  $(document.getElementById(id)).toggle();
}

Now the actual problem: your id parameter getting passed in is an object, that's the only thing that'd result in the error you're getting with the first version above:

Uncaught Syntax error, unrecognized expression: #[object Object]

id is getting a .toString() when you concatenate it with "#", resulting in "#[object Object]". Your id parameter needs to be a string, not an object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜