如何根据输入的内容更改输入的标题?

How to change the title of input based on the input being typed?

我有一个空的输入框,我可以在其中输入任何内容。当我将鼠标悬停在输入上时,它应该将标题显示为输入框中的文本。

<input type="text" />
$(document).ready(function() {
    $('input').mouseover(function() {
        var $txt = $('input').text();    
        $('input').attr('title', $txt);
    })
})

Live Demo

Use keyup event to update the title attribute. As mentioned by Alex, Using this in the handler will read the value of the current input element and will update title attribute of the current input element. $('input') will select all the input tag elements and .attr() will set attribute for all the matched elements.

另请注意,您应该使用 .val() 从输入中获取值而不是 text()

试试这个:

$(document).ready(function() {
  $('input').keyup(function() {
    var $txt = $(this).val();
    $(this).attr('title', $txt);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" />

编辑:或使用input,当<input><textarea>的值时同步触发事件元素已更改。 使用 .trigger('input') 只是为了确保在调用 input 事件之前设置 title initially

试试这个:

$(document).ready(function() {
  $('input').on('input', function() {
    var $txt = $(this).val();
    $(this).attr('title', $txt);
  });
  $('input').trigger('input');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" value='Hello' />

您可以使用输入事件侦听器:

$(document).ready(function() {
  $('input').on('input',function(e) {
    var $txt = $(e.target).val();
     $(e.target).attr('title', $txt);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" />

使用 .val() 方法从输入中获取值,

您将 .val() 值添加到 title 属性,您就完成了!!

如果您有多个 input 元素,请使用 $(e.target) 作为选择器来获取值和设置标题属性。

$("input[type=text]").on("input", function() {
   $(this).attr("title", $(this).val());
});

您可以简单地使用上面的脚本来完成您的要求。

使用onInput事件将承接pastedrop等所有输入格式。

工作 Fiddle : https://jsfiddle.net/6pys5hoy/

<script tyep="text/javascript">
$(document).ready(function(){
    function set_title($txt)
    {
        $('input').attr('title', $txt);
    }

   $(document).on('keyup','input',function()
   {
        var $txt = $(this).val();    
        set_title($txt);
    });

});
</script>

html

<body>
     <input type="text" />
</body>

您应该使用 input 事件来设置 title 属性,因为这会在人们直接在字段中键入内容以及在其中粘贴内容时捕捉到。另请注意,为了遵循最佳实践,您应该使用 prop() 而不是 attr() 来设置 title。试试这个:

$('input').on('input', function() {
    $(this).prop('title', function() {
        return this.value;
    });
})

Working example

如果你想用JavaScript设计,这就是它的样子

var input = document.getElementById('INPUT');
input.addEventListener('mouseup' , () => {
    input.setAttribute('title', input.value)
})
<input type="text" id='INPUT' />