【问题标题】:JS: Replace a link with another word. Nested quotes + escape codesJS:用另一个词替换链接。嵌套引号 + 转义码
【发布时间】:2014-09-23 01:48:14
【问题描述】:

从一个全新的纯 HTML 文档开始,并且只使用 HTML 和 Javascript。

在上面加上超链接的单词“食物”

点击“食物”时,应替换为“肉类和蔬菜”

点击“肉”时,应替换为“培根猪肉”

点击“蔬菜”后,应替换为“胡萝卜加豌豆”

点击''pork''时,应该换成''tough and chefy''

点击''tough''时,应替换为''burnt and salty''

(等等)

我一直在尽力做到这一点,但我遇到了转义码问题。

这是我的代码:

<span id="food"><a href="#" onclick="document.getElementById('food').innerHTML='<span id=\'meat\'><a href=\'#\' onclick=\'var meat = &#34;<span id=&#38;pork&#38;><a href=#\ onclick=alert(2)>pork</a></span> with bacon&#34;; document.getElementById(&#34;meat&#34;).innerHTML = meat\'>meat</a></span> and <span id=\'vegetables\'><a href=\'#\' onclick=\'var vegetables = &#34;carrots plus peas&#34;; document.getElementById(&#34;vegetables&#34;).innerHTML = vegetables\'>vegetables</a></span>'">food</a></span>

它正在运行:http://jsfiddle.net/jshflynn/L6r5rrfx/

很抱歉,它没有间隔,但这会引发错误。

请注意,''alert(2)'' 周围没有分隔字符,我不知道如何让它说 alert(''Hello'')。

我觉得必须有一些递归方式来做到这一点,但我不确定。

提前致谢。尤其是如果你能解决完整的问题。

【问题讨论】:

  • 哈哈老实说,这很有趣!我会尽快给你一个优雅的解决方案。

标签: javascript html quote html-escape-characters


【解决方案1】:

给你,你明白了:http://jsfiddle.net/8bhd8njh/

    function bind(obj, evt, fnc) {
        // W3C model
        if (obj.addEventListener) {
            obj.addEventListener(evt, fnc, !1);
            return !0;
        }
        // Microsoft model
        else if (obj.attachEvent) {
            return obj.attachEvent('on' + evt, fnc);
        }
        // Browser don't support W3C or MSFT model, go on with traditional
        else {
            evt = 'on'+evt;
            if(typeof obj[evt] === 'function'){
                // Object already has a function on traditional
                // Let's wrap it with our own function inside another function
                fnc = (function(f1,f2){
                    return function(){
                        f1.apply(this,arguments);
                        f2.apply(this,arguments);
                    }
                })(obj[evt], fnc);
            }
            obj[evt] = fnc;
            return !0;
        }
    }

    String.prototype.supplant = function (a, b) {
        return this.replace(/{([^{}]*)}/g, function (c, d) {
            return void 0!=a[d]?a[d]:b?'':c
        })
    };

    var data = {
        food : '{meat} and {vegetables}',
        meat : '{pork} and {beef}',
        pork : '{tough} and {chewy}',
        tough : '{burnt} and {salty}',
        vegetables : '{carrots} and {peas}'
    };

    var classname = 'game-clickable';

    var init = function(obj, data) {
        var template = '<span class="{classname}">{text}</span>';

        obj.innerHTML = obj.innerHTML.replace(/{([^{}]*)}/g, function(a,b) {
            return template.supplant({
                classname : data[b] ? classname : '',
                text : b
            }, !0)
        });

        var objects = document.getElementsByClassName('game-clickable');

        for (var i = 0; i < objects.length; i++) {
            bind(objects[i], 'click', (function(o) {
                return function() {
                    if (!data[o.innerHTML]) {
                        return;
                    }
                    var parent = o.parentNode;

                    var span = document.createElement('SPAN');
                    span.innerHTML = data[o.innerHTML];

                    parent.insertBefore(span, o);
                    parent.removeChild(o);

                    init(parent, data);
                }
            })(objects[i]));
        }
    };

    init(document.getElementById('word-game'), data);
.game-clickable {
    cursor: pointer;
    text-decoration: underline;
}
<div id="word-game">
    {food}
</div>

【讨论】:

【解决方案2】:

我认为您正在寻找类似以下的内容:

var replacements = {
  "food" : "meat and vegetables",
  "meat" : "pork with bacon",
  "vegetables" : "carrots plus peas",
  "pork" : "tough and chewy",
  "tough" : "burnt and salty" 
};

function replaceAnchor(a) {
  var elementType = "";
  var lastElementType = "";
  var target = a.innerHTML;
  var replacement = replacements[target];
  var words = replacement.split(' ');
  var newElement = {};
  for(var i = 0; i < words.length; i++) { 
  	var word = words[i];
  	if (replacements[word]) {
  	  elementType = "a";
  	} else {
  	  elementType = "span";
  	}
  	
  	if (elementType === "a" || elementType != lastElementType) {
  	  newElement = document.createElement(elementType);
  	  if (elementType === "a") {
  	    newElement.onclick = function(e) { 
  		  replaceAnchor(this);
  		  e.preventDefault();
  		};
  	  }						
  	  a.parentNode.insertBefore(newElement, a);
  	}
  	
  	if (elementType == "span") {
  	  newElement.innerHTML = newElement.innerHTML + " " + word + " ";
  	} else {
  	  newElement.innerHTML += word;
  	}
  	lastElementType = elementType;
  	
  }
  a.parentElement.removeChild(a);
  return false;
}
a {
  text-decoration : underline;
  color : blue;
  cursor: pointer;
}
&lt;a onclick="return replaceAnchor(this);"&gt;food&lt;/a&gt;

【讨论】:

  • 它应该只替换点击的单词,而不是第一个可用的短语
  • 我也给你点赞,我喜欢
猜你喜欢
  • 2021-02-04
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 2011-05-11
  • 2021-07-27
  • 1970-01-01
相关资源
最近更新 更多