пожалуйста, как я могу раскрасить слово, введя его порядковый номер с помощью jQuery?
пример:
<div id = "example">
<p class = "txt">hello my best friend</p>
<input type = "number" id = "myNumber">
<button>Color it</button>
</div>
когда я ввожу (2,3) и нажимаю кнопку, слова «мой» и «лучший» становятся желтыми (# ffbe00)
Используйте это здесь jsfiddle
(function ($) {
var SetColor=function(){
var str=$(".txt").text().split(' ');
$(".txt").empty();
var filter=$("#myNumber").val().replace('(','').replace(')','').split(',');
for(var i=0;i<str.length;i++){
for(var j=0;j<filter.length;j++){
if ((i+1)==filter[j]){
str[i] = "<span style='color: yellow;'>"+str[i]+"<span>";
}
}
$(".txt").append(str[i]+" ");
}
}
$("#btn").on("click",SetColor);
})(jQuery);
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "example">
<p class = "txt">hello my best friend</p>
<input type = "text" id = "myNumber">
<button id = "btn">Color it</button>
</div>