我有一个readonly
textarea,其值不断变化。现在我希望页面不断更新其值并返回结果,如果它与提供的字符串匹配。这是我尝试过的,但它不起作用
var string = "This is my house";
$('#textarea').bind('input', function() {
if ($(this).val() === string.trim()) {
$('#message').html('matching').css('color', 'green');
} else $('#message').html('not matching').css('color', 'red');
});
答案 0 :(得分:1)
我认为您无法收听input
事件,因为textarea是readonly
,您可以做的是触发input
- 或任何其他事件< / em> - 在更改textarea的文本内容的相同代码中使用.trigger()
var string = "This is my house", ta = $('#textarea'), msg = $('#message'),
newContent = 'just dummy text'; // replacement text, change it to see the result
ta.on('input', function() {
if ($(this).val() === string.trim()) { msg.html('matching').css('color', 'green'); }
else { msg.html('not matching').css('color', 'red'); }
});
$('#btn').on('click', function() {
ta.text(newContent).trigger('input'); // trigger input event as text content is changed
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="btn">Change it</button><br>
<textarea readonly name="" id="textarea" cols="30" rows="5">This is my house</textarea>
<hr><div id="message"></div>
答案 1 :(得分:1)
你可以做这样的事情
var string = 'This is my house';
var array = ['Lorem ipsum dolor sit amet', 'consectetur adipisicing elit', 'This is my house', 'quae aperiam solut'];
var counter = 0;
$('textarea').click(function() {
if(array[counter] == string.trim()) {
$('.result').text('Matching').css('color', 'green');
} else {
$('.result').text('Not matching').css('color', 'red');
}
$('textarea').text(array[counter]);
counter = (counter + 1) % array.length;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea readonly placeholder="Click Me" class="textArea"></textarea>
<div class="result"></div>
&#13;