仅显示html中第一个逗号的内容

时间:2017-09-14 12:00:15

标签: javascript jquery html css3

我有以下html实例:

<span class="booking-detail"><b>12 hours, 12 hours, 12 hours</b></span>

除了内容包括“会议室,会议室,会议室”等内容外,还有其他相同标记的实例。

我基本上只想显示“12小时”和“会议室”等,并在第一个逗号后隐藏所有内容。无论我是通过包装第一个逗号来实现这一点,还是用一个跨度后面的所有内容,然后我隐藏或替换html内容并不重要。

谢谢

5 个答案:

答案 0 :(得分:1)

循环项目,将文本拆分为逗号,然后将其添加回元素。

$('.booking-detail b').each( function() {
  var text = $(this).html(); /* get the text */
  var textParts = text.split(','); /* split on the comma */
  $(this).html(textParts[0]); /* insert first array part */
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="booking-detail"><b>12 hours, 12 hours, 12 hours</b></span><br />
<span class="booking-detail"><b>14 hours, 12 hours, 12 hours</b></span><br />
<span class="booking-detail"><b>15 hours, 12 hours, 12 hours</b></span>

对于动态内容(基于评论)

$('.booking-detail').each( function() {
  var b = $(this).find('b');
  var text = b.html(); /* get the text */
  var textParts = text.split(','); /* split on the comma */
  b.html(textParts[0]); /* insert first array part */
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="booking-detail"><b>12 hours, 12 hours, 12 hours</b></span><br />
<span class="booking-detail"><b>14 hours, 12 hours, 12 hours</b></span><br />
<span class="booking-detail"><b>15 hours, 12 hours, 12 hours</b></span>

没有.each

的替代方案

$('.booking-detail b').html( function(i,text) {
  return(text.split(',').splice(0,1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="booking-detail"><b>12 hours, 12 hours, 12 hours</b></span><br />
<span class="booking-detail"><b>14 hours, 12 hours, 12 hours</b></span><br />
<span class="booking-detail"><b>15 hours, 12 hours, 12 hours</b></span>

答案 1 :(得分:0)

尝试使用split()

$('.booking-detail b').each(function (idx, elem){

    var $elem = $(elem);
    $elem.text($elem.text().split(',')[0])'

});

答案 2 :(得分:0)

您可以在字符串中查找子字符串,如:

$builder->add('credit_card', CreditCardStripeTokenType::class, [
     'add_stripe_name' => 'name', // <---- \o/
]);

答案 3 :(得分:0)

var a = $('b').text().split(',');
$('b').text(a[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span><b>12 hours,12 hours, 12 hours</b></span>

答案 4 :(得分:0)

&#13;
&#13;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('.booking-detail b').each( function() {
  var text = $(this).html();   var textParts = text.split(',');   $(this).html(textParts[0]);
});
</script
</head>
<body>
<span class="booking-detail"><b>12 hours, 12 hours, 12 hours</b></span>
</body>
</html>
&#13;
&#13;
&#13;

希望这对你有用!谢谢