.replace无法在Firefox中运行?

时间:2018-02-10 07:35:59

标签: javascript jquery html

JS

$(document).ready(function(){
    $(document).on('click', 'div[id^="button-"]', function(e){
        e.preventDefault();

        var elementId = event.target.id.replace(/\D/g,'');
        $(".content-wrapper-" + elementId).css("display","inline");
    });
});

HTML

<div id="button-1"></div>
<div id="button-2"></div>
<div id="button-3"></div>

<div class="content-wrapper-1" style="display: none;">Test 1</div>
<div class="content-wrapper-2" style="display: none;">Test 2</div>
<div class="content-wrapper-3" style="display: none;">Test 3</div>

快速解释

获取所点击元素的ID并提取所有数字。例如&#34;按钮-9&#34;至&#34; 9&#34;。然后连接字符串.content-wrapper + ID并显示该容器的内容。*

这适用于Google Chrome,但不适用于Firefox。我可以把它分解为这一行:

var elementId = event.target.id.replace(/\D/g,'');

但我无法弄清楚这里有什么不对。一点帮助值得赞赏。谢谢。

2 个答案:

答案 0 :(得分:4)

您的行假定import React from 'react'; import { Field, reduxForm } from 'redux-form'; const renderField = ({ input, label, type, meta: { touched, error, warning } }) => ( <div> <input {...input} placeholder={label} type={type}/> {touched && error && <div className="EmployeeForm-error">{error}</div>} </div> ) const EmployeeForm = ({ addEmployee, fields: { name, surname}, handleSubmit }) => { return ( <form onSubmit={handleSubmit(addEmployee)}> <div> <Field name="name" type="text" component={renderField} label="name"/> </div> ... </form> );} 作为全局变量存在:

event

这是a non-standard property,Firefox不支持。您已经可以访问该事件作为回调的第一个参数:

event.target.id.replace(/\D/g,'');
^^^^^

答案 1 :(得分:0)

eventchromeIE中是全局的,但在fuckntion中定义的firefox中不是全局的,因此将event替换为e,以使其在所有浏览器。

$(document).ready(function(){
    $(document).on('click', 'div[id^="button-"]', function(e){
        e.preventDefault();

        var elementId = e.target.id.replace(/\D/g,'');
        $(".content-wrapper-" + elementId).css("display","inline");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML

<div id="button-1">11</div>
<div id="button-2">22</div>
<div id="button-3">33</div>

<div class="content-wrapper-1" style="display: none;">Test 1</div>
<div class="content-wrapper-2" style="display: none;">Test 2</div>
<div class="content-wrapper-3" style="display: none;">Test 3</div>