Javascript jQuery切换更改函数中按钮的内部html
我有两个要素Javascript jQuery切换更改函数中按钮的内部html,javascript,jquery,html,Javascript,Jquery,Html,我有两个要素 <div id="searchInput"> This is something </div> <button type="button" id="dugme" onclick="th()" > Show </button> 但是,当我想更改切换中的innerHTML时,什么都不会发生。这就是我所尝试的: function th(){ $(document).ready(function(){ var fo
<div id="searchInput">
This is something
</div>
<button type="button" id="dugme" onclick="th()" > Show </button>
但是,当我想更改切换中的innerHTML时,什么都不会发生。这就是我所尝试的:
function th(){
$(document).ready(function(){
var forma = document.getElementById("searchInput");
var dugme = document.getElementById("dugme");
$(forma).toggle(function(){
$(dugme).innerHTML = "Hide";
});
});
}
当您试图在jQuery对象上调用元素属性
innerHTML
时,会出现问题,您可以使用html()
,但由于您只更改文本,因此最好使用.text()
如下:
$(dugme).text("Hide");
您可以使用.is(':visible')
切换文本,如下所示:
forma.toggle(function() {
dugme.text(forma.is(':visible') ? "Hide" : "Show");
});
函数th(){
$(文档).ready(函数(){
var forma=$(“#搜索输入”);
var dugme=$(“#dugme”);
形式切换(函数(){
dugme.text(形式为(“:可见”)?“隐藏”:“显示”);
});
});
}
这是一件大事
隐藏
您需要使用$(dugme.html(“隐藏”)因为$(dugme)
是jQuery对象。函数中也不需要document.ready
处理程序
函数th(){
var forma=document.getElementById(“searchInput”);
var dugme=document.getElementById(“dugme”);
$(形式)。切换(函数(){
$(dugme.html(“隐藏”);
});
}
这是一件大事
显示
尝试以下操作:
function th(){
var forma = $("#searchInput");
var dugme = $("#dugme");
forma.toggle(function(){
var txt = forma.is(':visible') ? 'Hide':'Show';
gugme.text(txt);
});
}
Html
您正在混合纯javascript和jquery,尝试用一种特定的样式编写代码。也不需要在从html onclick属性调用的函数中使用就绪事件处理程序。@Rorymcrossan,正如OP所述。然而,这是没有用的。我也更正了我的答案。var txt=forma.is(':visible')?'隐藏':'显示'代码>帮助切换。谢谢你!您正在将另一个答案标记为正确,但它显然没有切换文本“隐藏/显示”您有什么理由吗?!
function th(){
var forma = $("#searchInput");
var dugme = $("#dugme");
forma.toggle(function(){
var txt = forma.is(':visible') ? 'Hide':'Show';
gugme.text(txt);
});
}
<div id="searchInput">
This is something
</div>
<button type="button" id="dugme">Hide</button>
$('#dugme').click(function(){
if ($.trim($(this).text()) == 'Hide') {
$(this).text('Show');
$('#searchInput').hide();
} else {
$('#searchInput').show();
$(this).text('Hide');
}
});