我有一个jquery事件,该事件在单击某个按钮时触发,然后检查某个容器段落的值是否完全等于预定义变量。如果为true,我希望将其替换为我定义的其他变量,并更改完全不同的元素的文本。
不过,此刻,我的代码将触发该部分以更改其他元素,即使该段落不等于该值(在本例中为x)。有没有办法使这项工作?
var x = 'a string';
var y = 'a different string';
$('#element-container').on('click', '#button1', function (){
$('#element p').filter(function() {
return $(this).html() == x;
}).replaceWith('<p>' + y + '</p>'); // This works as intended
$('.tooltip p').text('some new text here'); // This however, fires wiether #element p == x or not
});
的HTML
<div id="element-container">
<div id="element"><p>Text</p></div>
<button id="button1">button</button>
<div class="tooltip"><p>Some text</p></div>
</div>
最佳答案
var x = 'a string';
var y = 'a different string';
$('#element-container').on('click', '#button1', function (){
var elems = $('#element p').filter(function() {
return $(this).html() == x;
});
if (elems.length) { // check if any elements matched
elems.replaceWith( $('<p />', {text: y}) );
$('.tooltip p').text('some new text here');
}
});