2016-08-06 2 views
2

Мне нужно изменить текст и текст «____» на «Word», щелкнув по нему. Я не хочу иметь кнопку.Как поменять текст взад и вперед при нажатии на него?

Я вижу, что this page описывает именно то, что мне нужно, особенно способ CSS-Only, но когда я пытаюсь использовать его в редакторе TryIt, либо он, либо jQuery-Way не работает.

Вот CSS Путь:

</style> 
#example { 
position: relative; 
} 
#example-checkbox { 
display: none; 
} 
#example-checkbox:checked + #example:after { 
content: "Hide"; 
position: absolute; 
top: 0; 
left: 0; 
right: 0; 
bottom: 0; 
background: white; 
} 
</style> 

<input id="example-checkbox" type="checkbox"> 
<label for="example" id="example">Show</label> 
+0

Где текст _ "" ____ "" _ в 'html' на вопрос? – guest271314

+0

oh, данный код копируется из ссылки. Он должен быть заменен на 'Show' – Ooker

ответ

2

Это код, который будет соответствовать вашим требованиям.

<!DOCTYPE html> 
 
<html> 
 

 
<body> 
 
    This is a paragraph. Click on the next word -&gt; <span id="word" onclick="toggle()">____</span> &lt;- Have you clicked on previous word. 
 

 
    <p id="demo"></p> 
 

 
    <script> 
 
    function toggle() { 
 
     var word = document.getElementById("word").innerHTML; 
 
     if (word.split('_').join('').trim().length === 0) { 
 
     document.getElementById("word").innerHTML = "word"; 
 
     } else { 
 
     document.getElementById("word").innerHTML = "_____"; 
 
     } 
 
    } 
 
    </script> 
 
</body> 
 

 
</html>


EDIT # 2

Ниже фрагмент кода будет слово в соответствии с вашими обновленными требованиями.

В приведенном ниже коде просто просмотрите сценарий в разделе <head>.

<script> 
    var words = []; 

    words.push('vocabulary'); 
    words.push('lexicon'); 
    </script> 

Здесь, вы просто должны нажать слова, которые вы хотите, чтобы переключиться с _____ в массиве words. После того, как слова будут помещены в этот массив, они автоматически преобразуются, назад и вперед, чтобы подчеркнуть. Просто нажмите любое слово в этом массиве из абзаца и посмотрите сами переходы.

span { 
 
    color: red 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <script> 
 
    var words = []; 
 

 
    words.push('vocabulary'); 
 
    words.push('lexicon'); 
 
    </script> 
 

 
</head> 
 

 
<body> 
 

 
    <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. 
 
    </p> 
 

 
    <script> 
 
    function toggle(element) { 
 
     if (element.innerHTML.split('_').join('').trim().length === 0) { 
 
     element.innerHTML = element.getAttribute("word"); 
 
     } else { 
 
     element.innerHTML = "_______"; 
 
     } 
 
    } 
 

 
    $.each(words, function(index, value) { 
 
     var replacestr = new RegExp(value, "g"); 
 
     $("p#demo:contains('" + value + "')").html(function(_, html) { 
 
     return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)"> ' + value + ' </span>') 
 
     }); 
 
    }); 
 
    </script> 
 
</body> 
 

 
</html>


EDIT # 3

Если вы хотите ________ появляться первые при загрузке страницы просто заменить

return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)"> ' + value + ' </span>') 

с

return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">____________</span>') 

Конечный код будет:

span { 
 
    color: red 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <script> 
 
    var words = []; 
 

 
    words.push('vocabulary'); 
 
    words.push('lexicon'); 
 
    </script> 
 

 
</head> 
 

 
<body> 
 

 
    <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. 
 
    </p> 
 

 
    <script> 
 
    function toggle(element) { 
 
     if (element.innerHTML.split('_').join('').trim().length === 0) { 
 
     element.innerHTML = element.getAttribute("word"); 
 
     } else { 
 
     element.innerHTML = "_______"; 
 
     } 
 
    } 
 

 
    $.each(words, function(index, value) { 
 
     var replacestr = new RegExp(value, "g"); 
 
     $("p#demo:contains('" + value + "')").html(function(_, html) { 
 
     return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">_______</span>') 
 
     }); 
 
    }); 
 
    </script> 
 
</body> 
 

 
</html>


РЕДАКТИРОВАТЬ # 4

Следующий код будет работать для обоих множественных и сингулярности:

Просто измените строку:

var replacestr = new RegExp(value, "g"); 

к:

var replacestr = new RegExp('\\b'+value+'\\b', "g"); 

Окончательный код будет выглядеть так:

span { 
 
    color: red 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <script> 
 
    var words = []; 
 

 
    words.push('vocabulary'); 
 
    words.push('lexicon'); 
 
    words.push('lexicons'); 
 
    
 
    </script> 
 

 
</head> 
 

 
<body> 
 

 
    <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that's added, so don't forget to push 'lexicons' in your array. 
 
    </p> 
 

 
    <script> 
 
    function toggle(element) { 
 
     if (element.innerHTML.split('_').join('').trim().length === 0) { 
 
     element.innerHTML = element.getAttribute("word"); 
 
     } else { 
 
     element.innerHTML = "_______"; 
 
     } 
 
    } 
 

 
    $.each(words, function(index, value) { 
 
     var replacestr = new RegExp('\\b'+value+'\\b', "g"); 
 
     $("p#demo:contains('" + value + "')").html(function(_, html) { 
 
     return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">_______</span>') 
 
     }); 
 
    }); 
 
    </script> 
 
</body> 
 

 
</html>

+0

Спасибо, но у меня есть несколько разных слов для замены. Таким образом, вместо слова * word *, но также * словарного запаса *, * lexicon * и т. Д. Следует заменить пробел «______». – Ooker

+0

ОК .... Я буду обновлять свой ответ соответственно ... просто дай мне пару минут –

+0

спасибо. Я попытался использовать '.replace (" _____ ", word);' и 'innerHTML = word;', но ни одна из этих работ – Ooker

2

Это то, что вы ожидаете?

<input id="example-checkbox" type="checkbox"> 
<label for="example-checkbox" id="example">Show</label> 

Примечание атрибут for в label - он должен иметь id в input флажком

#example { 
 
    position: relative; 
 
    cursor: pointer; 
 
} 
 
#example-checkbox { 
 
    display: none; 
 
} 
 
#example-checkbox:checked + #example:after { 
 
    content: "Hide"; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    background: white; 
 
}
<input id="example-checkbox" type="checkbox"> 
 
<label for="example-checkbox" id="example">Show</label>

2

атрибут лейбла for должен содержать идентификатор флажком

#example { 
 
    position: relative; 
 
} 
 
#example-checkbox { 
 
    display: none; 
 
} 
 
#example-checkbox:checked + #example:after { 
 
    content: "Hide"; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    background: white; 
 
}
<input id="example-checkbox" type="checkbox"> 
 
<label for="example-checkbox" id="example">Show</label>

1
<label id="example-five" for="example-five-checkbox">_____</label> 

Ссылка: https://jsfiddle.net/n1rb2y57/ Но посмотрите на что вы выбираете надлежащий цвет фона в CSS согласования с сайта цвета.

Смежные вопросы