如果文本框值匹配,则使该特定标签文本为“是”,否则为“否”

If text box value matches then make that specific label text to yes else no

本文关键字:文本 标签 如果      更新时间:2023-09-26

我试着检查标签的文本是否与文本框匹配如果匹配,然后使特定的标签文本为yes否则否,但在我的代码中我不确定是什么错了,但这并没有发生,它显示"no"它自我

演示HTML

<input class="master" value="1">
    <label class="user_label" >1</label>
            <label class="user_label" >0</label>
        <label class="user_label" >1</label>

JS:

$(function() {
      var master = $('input.master').get(0).value; // get the master value
    var fn = function() {
        return this.text === master ? "yes" : "noo";//if current text-box matches master,then yes else no
    };
    $('label.user_label').text(fn); // loop and replace text for each user input

});

this.text将在fn中成为undefined,因为this是一个DOM节点,它不具有text属性。

你可以把它包装成一个jQuery对象,并使用text()方法:

var fn = function() {
    return $(this).text() === master ? "yes" : "noo";
}
http://jsfiddle.net/L6d39f10/5/

您可以将代码简化如下, text() 回调函数中的第二个参数引用旧的文本值。您可以使用 val() 在jQuery中获取值。

var val = $('input.master').val();
$('.user_label').text(function(i, text){
  return val === text ? 'yes' : 'no';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="master" value="1">
<label class="user_label">1</label>
<label class="user_label">0</label>
<label class="user_label">1</label>

当fn传入$('label.user_label').text(fn)时,上下文发生了变化,但仍然是这样。文本未定义。使用this.textContent、this.innerHTML(美元)。text ()

使用文本比较,然后修改它,使逻辑奇怪,它应该是这样的吗?

	$(function() {
	  $('input.master').keyup(function() {
	    var master = $(this).val(); // get the master value
	    var fn = function() {
	      return $(this).attr('data-val') === master ? "yes" : "noo"; //if current text-box matches master,then yes else no
	    };
	    $('label.user_label').text(fn); // loop and replace text for each user input
	  });
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="master" value="">
<label class="user_label" data-val="1"></label>
<label class="user_label" data-val="0"></label>
<label class="user_label" data-val="1"></label>

$(function() {
    var master = $('input.master').get(0).value; // get the master value
    $('label.user_label').each(function(){
      if($(this).text() === master){
        $(this).text("yes");
      }else{
        $(this).text("no");
      }
    });

});