![](/img/trans.png)
[英]how to check if a string contains substring and color it in javascript?
[英]How to check if a string contains a specific substring
我正在處理一個簡單的if / else jquery語句,但該變量遇到了一些麻煩。 我需要做的是檢查var是否為true。 在我的情況下,我希望它檢查其中是否有“不推動”功能。 如果為true,則html必須更改為“ lol”。 如果沒有,它將給出一個簡單的警報。 有人可以在這里給我一些指導嗎?
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width" />
<title>Untitled Document</title>
<link href="mobile.css" rel="stylesheet" type="text/css" media="only screen and (max-width: 480px)" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#nietklikken').click(function() {
var n = $(this).html('dont push');
if (n == "$(this).html('dont push')"){
$(this).html('lol')
} else {
alert('lolz');
}
});
});
</script>
</head>
<body>
<button type="button" id="nietklikken">dont push</button>
</body>
</html>
$(this).html()
將get
innerhtml值,而$(this).html(arg)
將set
innerhtml值。 正確的用法如下。
$('#nietklikken').click(function() {
if ($(this).html().indexOf('dont push') > -1){
$(this).html('lol')
} else {
alert('lolz');
}
});
您應該在jquery docs中閱讀更多內容。
更新 :現在將檢查innerhtml是否包含“不推送”。
您可以使用' indexOf '運算符,該運算符應告訴您一個字符串是否包含另一個字符串。 嘗試-
if ($(this).html().indexOf('dont push') != -1){
$(this).html('lol')
} else {
alert('lolz');
}
通常,您可以使用這樣的函數
function HasSubstring(string,substring){
if(string.indexOf(substring)>-1)
return true;
return false;
}
一個有效的javascript代碼,用於檢查string是否包含特定的單詞/子字符串:
var inputString = "this is my sentence";
var findme = "my";
if ( inputString.indexOf(findme) > -1 ) {
out.print( "found it" );
} else {
out.print( "not found" );
}
您可以通過不帶任何參數的html()
方法來獲取元素的HTML內容,如下所示:
var innerHtml = $(someElement).html();
然后可以使用indexOf
檢查字符串是否存在,如下所示:
var position = "Find the string".indexOf("the");
// position = 5
如果給定的字符串不存在, indexOf
將返回-1。
var position = "Find the string".indexOf("notFound");
// position = -1
然后,您可以在if
語句中使用它,如下所示
if($(someElement).html().indexOf("dont push") >-1)
{
// Required action here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.