我正在使用jQuery,我想将一些方法转换为本地JavaScript代码。
在jQuery中,我们像一样使用
$("div").toggle()
是否可以转换为类似的JavaScript
document.getElementById("id").callfunction();
是的,你可以做到。如果你对其他答案感到满意,说你必须创建新的函数,你必须调用它。那就去吧。
否则,如果您真的想遵循语法,那么它是相当简单和可行的。(看起来很漂亮的事实)
这就是你可以做到的:
Element.prototype.toggle = function() {
if ( this.style.display == '' || this.style.display == 'block' ) {
alert ( "Changing display to NONE ");
this.style.display = 'none';
}else{
this.style.display = 'block';
alert ( "Changing display to BLOCK ");
}
}
请记住IE8不支持Element Prototype,但Chrome、FF、Safari支持
运行它
- 在此页面中打开铬控制台
- 复制粘贴到上面的代码,并在中运行控制台
- 现在在控制台
document.getElementById('question-header').toggle()
中执行此操作[这将在此页面中显示/隐藏问题标题]
不清楚自己想要什么,但如果这有帮助:
function toggle_item(id){ // your div id
var this_item = document.getElementById(id);
if( this_item.style.display == 'block' ) {
this_item.style.display = 'none';
}
else {
this_item.style.display = 'block';
}
}
Html:-
<button onclick="toggleCheck('contentDiv')">Toggle</button>
<div ID="contentDiv" style="display:block;">This is content.</div>
Javascript:-
function toggleCheck(divId) {
var divId = document.getElementById(divId);
// Toggle
divId.style.display == "block" ? divId.style.display = "none" :
divId.style.display = "block";
}
工作演示
原因是的。您需要实现一个函数callfunction。然后添加此函数作为元素的原型函数。有关详细信息,请查看以下示例代码:
<!DOCTYPE HTML>
<html>
<head>
<title>test</title>
</head>
<body>
<div id="test">Hello, world!</div>
<button onclick="test()">toggle</button>
<script>
var test = function() {
document.getElementById("test").callfunction();
};
var callfunction = function() {
if (this.style.display == "none") {
this.style.display = "block";
} else {
this.style.display = "none";
}
};
// set callfunction as prototype function of all elements
Element.prototype.callfunction = callfunction;
</script>
</body>
</html>
经过测试,这可以在IE8、IE9、chrome和ff中工作。