Следующий сценарий даст сообщение в Chrome и IE:
<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here
return "Please click 'Stay on this Page' and we will give you candy";
};
</script>
Chrome [/g0]
IE [/g1]
в Firefox вы получите общее сообщение
[/g2]
Механизм синхронный, поэтому серверные вызовы на задержку не будут работать, вы все равно можете подготовить механизм, подобный модальное окно, которое отображается, если пользователь решит остаться на странице, но не сможет помешать ему уйти.
Ответ на вопрос в комментарии
F5 снова запустит событие, так что Atl + F4.
Похоже, хорошая возможность использовать цикл:
mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
my_string = my_string.replace(k, v)
Более быстрый подход, если вы не возражаете против скобок будет:
mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
my_string = my_string.replace(k, v)
Вы можете легко использовать string.maketrans () для создания строки сопоставления для передачи в str.translate ():
import string
trans = string.maketrans("ABCDE","12345")
my_string = my_string.translate(trans)
Также посмотрите в str.translate ()
. Он заменяет символы в соответствии с отображением, которое вы предоставляете для строк Unicode, или иначе должен быть указан, на что заменить каждый символ с chr (0) на chr (255).
If you want to get the wrong answer, slowly, then use string.replace in a loop. (Though it does work in this case of no overlap among the patterns and replacements.)
For the general case with possible overlaps or a long subject string, use re.sub:
import re
def multisub(subs, subject):
"Simultaneously perform all substitutions on the subject string."
pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs)
substs = [s for p, s in subs]
replace = lambda m: substs[m.lastindex - 1]
return re.sub(pattern, replace, subject)
>>> multisub([('hi', 'bye'), ('bye', 'hi')], 'hi and bye')
'bye and hi'
For the special case of 1-character patterns and 1- or 0-character replacements, use string.maketrans.
replaceDict = {'A':'1','B':'2','C':'3','D':'4','E':'5'} for key, replacement in replaceDict.items(): my_string = my_string.replace( key, replacement )