2015-07-01 55 views
0
$("button").click(function() { if ($("#showHideButton").val() == "Read More2") 
    $("#showHideButton").val(function(){ 
    return "Read Less" 
});}); 

我试图让按钮切换值。jquery检查和更改按钮值

+0

请显示您的HTML。理想情况下,制作一个演示问题的[stack snippet](http://meta.stackoverflow.com/questions/270944/feedback-requested-stack-snippets-2-0)。 – Barmar

+1

如果是'

+0

为什么你用一个函数返回“Read Less”? 另外,您应该使用“===”来支持“==”作为经验法则 - 在这种情况下,它可能并不重要,但在其他情况下肯定会有所影响。所以建议养成只使用“===”的习惯。 –

回答

0

该代码不言自明。

工作例如:

$("button").click(function() { 
 
    if ($("#showHideButton").text() == "Read More") 
 
     $("#showHideButton").text("Read Less"); 
 
    else 
 
     $("#showHideButton").text("Read More"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="showHideButton">Read More</button>

0

你可以做这样的事情:

$("button").on('click', function() { 
    if($(this).text() == 'Read More') { 
     $(this).text('Read Less'); 
    } else { 
     $(this).text('Read More'); 
    } 
}); 

按理说,所以如果你是疯了担心开销switch/case被执行比if/else好, ,你可以这样做。但我不会担心,因为它非常简单。你可能甚至无法看到两者之间的差异。