Jquery切换HTML中两个特定单词之间的内容

时间:2015-12-31 15:46:24

标签: javascript jquery html regex

我有以下Javascript代码在-a-& amp;之间切换内容-ea-。 运行时,我的HTML中有一个“查看答案”链接。 现在,我想表现得像:--example-& -enampleample-,我应该在-sample-&之间有一个“查看示例”链接。 -endsample-,我应该有一个“查看样本”链接等等。

小提琴https://jsfiddle.net/eoc74009/6/

    $(document).ready(funciton(){
    initToggleContent();
});

initToggleContent = function(){
    var p_content = $(".content").html();
    p_content = p_content.replace(new RegExp("-a-","g"),"<div class='hidden toggle-content'>")
  p_content = p_content.replace(new RegExp("-ea-","g"),"</div><hr>")
  $(".content").html(p_content);
  $("<a class='toggle-button'>View Answer</a>").insertBefore(".toggle-content");
  $(document).on('click',".toggle-button",function(){
    $(this).next(".toggle-content").toggleClass("hidden");
    if($(this).html()==="View Answer"){
        $(this).html("Hide Answer");
    }
    else{
    $(this).html("View Answer");
    }
  });

}

2 个答案:

答案 0 :(得分:1)

您可以使用此代码:

p_content = p_content.replace(/-([^\-]+)-([\s\S]*)-end\1-/gm, function(_, name, content) {
   return '<a class="toggle-button" data-name="' + name +
    '">View ' + name + '</a>' +
    '<span class="hidden toggle-content">' +
    content + '</span><hr>';
});

span而不是div,因为div不能在p标签内。

正则表达式解释

-([^\-]+)-将匹配破折号,任意数量的非短划线和破折号

([\s\S]*)将匹配任何内容,包括换行符

-end\1-将匹配短划线结尾和与之匹配的名字

parentesis用作捕获组,因此您可以替换它们。

修改了点击处理程序:

$(document).on('click',".toggle-button",function(){
    $(this).next(".toggle-content").toggleClass("hidden");
    var name = $(this).data('name');
    if($(this).html()==="View " + name){
        $(this).html("Hide " + name);
    }
    else{
        $(this).html("View " + name);
    }
});

<强> JSFIDDLE

答案 1 :(得分:0)

我对此进行了一些愚蠢的处理并不断迭代答案以提出更具框架性的解决方案,这允许您创建自己的html片段,看起来有点像jsx,并依靠css复选框来切换内容而不是绑定js,如果管理不当可能会很麻烦。

https://jsfiddle.net/eoc74009/9/

var
  $content = $('.content'),
  __id = makeNumberIterator(),
  text = $content.html();

// this object holds the bbcode functions
var codes = {
  sample: bbcode('sample', function(content, id) {
    return (
      '<section class="sample">' +
        '<input type="checkbox" class="sample-checkbox" id="sample-' + id + '">' +
        '<label for="sample-' + id + '" class="sample__label">Sample</label>' +
        '<div class="sample__content"><h3>' + content + '</h3></div>' +
      '</section>'
    );
  }),
  link: bbcode('a', function(content, id) {
    return (
      '<section class="toggle">' +
        '<input type="checkbox" class="toggle__checkbox" id="toggle-' + id + '">' +
        '<label for="toggle-' + id + '" class="toggle__label">Answer</label>' +
        '<div class="toggle__content">' + content + '</div>' +
      '</section>'
    )
  })
}

$content.html(replaceWithCodes(text, codes));

/**
 * replaceWithCodes
 *
 * this funtion will call each of the bbcodes functions to replace the content
 *
 * @param {string} 	content 	html content from the page
 * @param {Object}	codes 		object of the bbcode functions
 */
function replaceWithCodes(content, codes) {
  for (var key in codes) {
    content = codes[key](content);
  }
  return content;
}

/**
 * bbcode
 *
 * this is a factory for a function to replace your -bbcode- with a template
 *
 * @param {string} 		code 			bbcode to find in text without hyphens
 * @param {Function} 	template 	jsx style function template, recieves content and id
 *
 * @returns {string} 						replaced template
 */
function bbcode(code, template) {
  return function(input) {
    var reg = new RegExp('-' + code + '-([^-]+)-end' + code + '-', 'gm');
    return input.replace(reg, function(_, content) {
      return template(content, __id());
    });
  }
}

/**
 * makeNumeberIterator
 *
 * this is a helper function to get a function which returns
 * an incrementing number
 *
 * @param {Number} 	initial 	initial value to iterate from
 */
function makeNumberIterator(initial) {
  var ii = initial || 0;
  return function() {
    return ii++;
  }
}
* {
  box-sizing: border-box;
}
.sample,
.toggle {
  margin: 1em 0;
}
input[type=checkbox] {
  -webkit-appearance: none;
  appearance: none;
}
input[type=checkbox] ~ label {
  background: #3cf;
  color: white;
  padding: .3em 1em;
  margin: 1em 0;
}
input[type=checkbox] ~ label:before {
  content: "View ";
}
input[type=checkbox] ~ .toggle__content,
input[type=checkbox] ~ .sample__content {
  display: none;
  padding: 1em;
  .3em;
}
input[type=checkbox]:checked ~ label:before {
  content: "Hide ";
}
input[type=checkbox]:checked ~ .toggle__content,
input[type=checkbox]:checked ~ .sample__content {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <h2>
Hello my name is bleh!
</h2>

  <p>
    -a- Happy new year man! How ya doing?! -enda- -sample- something something darkside -endsample-
  </p>

</div>