2017-12-01 23 views
0

"8:00"주위에 스팬을 만들어서 색을 바꿀 수있게해야합니다. 분명히 나는 ​​실제 html을 편집 할 수 없다.부분 문자열/텍스트 부분에 범위 추가

var justTheTime= $('.foo').text().split('The time is')[1]; 

하지만 주위의 범위를 추가하는 방법을 알아낼 수 없습니다 :

<span class="foo">The time is 8:00</span> 

나는 정확한 지점에 그것을 분할 할 수 있었다. 도움?

var withStyles = $('<span style="color:red">'+onlyTheDate+'</span>'); 
$(".foo").replace(justTheTime,withStyles); 

답변

0

.replace()은 jQuery 함수가 아닙니다. 자바 스크립트입니다. 또한 justTheTime 대신 정의되지 않은 변수 onlyTheDate을 추가하려는 것 같습니다.이 예에서 수정했습니다.

당신이 할 수있는 일은 replaceWith()이며, 수동으로 시간을 수동으로 입력하기 만하면됩니다. 당신이 <span> 자체에 The time is을 포장 할 수 있습니다 참고 :

var justTheTime = $('.foo').text().split('The time is')[1]; 
 
var withStyles = $('<span>The time is</span><span style="color:red">' + justTheTime + '</span>'); 
 
$('.foo').replaceWith(withStyles);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="foo">The time is 8:00</span>

희망이 도움이 :)

0

replace() 방법은 문자열이 아닌 jQuery를 요소에서 작동합니다.

정규식을 사용하여 범위의 내용을 바꾸고 .html()을 사용하여 업데이트하십시오.

$('.foo').html(function(i, oldtext) { 
    return oldtext.replace(/The time is (.*)/, 'The time is <span style="color:red">$1</span>'); 
}); 
0

당신은 한 번 /(\d{1,2}):(\d{1,2})/g이 하나 이상의 날짜가 있다면 그들 모두를 대체 할 수 있도록, 색상 모든 항목을 대체하지 않습니다 같은 하나 같은 형식의 문자열을 볼 수 있습니다

$('.foo').html(
 
    $('.foo').text().replace(/(\d{1,2}):(\d{1,2})/g, '<span class="red">$1:$2</span>') 
 
)
.red {color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="foo">The time is 8:00</span>

0

시도 뭔가 같은 :

var justTheTime = $('.foo').text().split('The time is')[1]; 
 
var spanText = "The time is <span style='color:red'>"+ justTheTime +"</span>"; 
 
$('.foo').html(spanText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<span class="foo">The time is 8:00</span>