如何在单击按钮时向模式添加文本

时间:2018-11-19 11:35:39

标签: javascript ajax twitter-bootstrap

我有这个模态

 <div class="modal fade" id="bankAssess" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabelBank" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabelBank">Bank Assess <span id="bankAssessBondId"></span></h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form>
                           <div class="credit-scoring">
                                <label for="credit-scoring" class="form-control-label">Credit Scoring:</label>
                                <input type="text" class="form-control" id="credit-scoring">
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary" id="submit-form-Bank">Submit</button>
                    </div>
                </div>
            </div>
        </div>

并且我想在单击以下按钮时在<span id="bankAssessBondId"></span>中添加文本

<button class="btn btn-success bank" type="button" data-toggle="modal" data-target="#bankAssess" value="bond3">
Bank Assess
</button>

由于我为此使用了多个按钮,因此我使用了如下的EventListener

var buttons = document.getElementsByClassName('btn btn-success bank');
    for(var i=0; i<buttons.length; i++){
        buttons[i].on("click", function(){
             $('#bankAssessBondId').append($(this).value)
        })
}

,但未检测到“单击”按钮事件。我怎样才能解决这个问题?

4 个答案:

答案 0 :(得分:0)

您的问题似乎是您正在尝试将jQuery on与发现不使用jQuery的元素一起使用。我的看法是,根据您要实现的目标,您有两种可能的解决方案。

  1. 使用addEventListener

     submitFormHandler = () => {
            console.log("FormHandler: " + this.state.message)
            let isFormValid = true;
            let dataToSubmit = {};
            const formCopy = this.state.form;
    
            var user = firebase.auth().currentUser;
    
            for (let key in formCopy) {
              isFormValid = isFormValid && formCopy[key].valid;
              dataToSubmit[key] = this.state.form[key].value;
            }
    
            if (isFormValid, user) {
              this.setState({
                loading: true
              });
    
              getTokens((value) => {
                const imageRef = firebase.storage().ref('images/').child(imageSource.uri)
                const dateNow = new Date();
                const expiration = dateNow.getTime();
                const form = {
                  ...dataToSubmit,
                  uid: value[3][1]
                }
    
                if (expiration > value[2][1]) {
                  this.props.autoSignIn(value[1][1]).then(() => {
                    setTokens(this.props.User.userData, () => {
    
                      this.props.addArticle(form, this.props.User.userData.token).then(() => {
                        this.setState({ modalSuccess: true })
                      })
                    })
                  })
                } else {
                  this.props.addArticle(form, value[0][1]).then(() => {
                    this.setState({ modalSuccess: true })
                  })
                }
              })
    
            } else {
              let errorsArray = [];
    
              for (let key in formCopy) {
                if (!formCopy[key].valid) {
                  errorsArray.push(formCopy[key].errorMsg)
                }
              }
    
              this.setState({
                loading: false,
                upload: true,
                hasErrors: true,
                modalVisible: true,
                errorsArray
              })
            }
          }
    
          showErrorsArray = (errors) => (
            errors ?
              errors.map((item, i) => (
                <Text key={i} style={styles.errorItem}> - {item}</Text>
              ))
              : null
          )
    
          clearErrors = () => {
            this.setState({
              hasErrors: false,
              modalVisible: false,
              errorsArray: []
            })
          }
    
          resetScreen = () => {
            const formCopy = this.state.form;
    
            for (let key in formCopy) {
              formCopy[key].valid = false;
              formCopy[key].value = "";
            }
    
            this.setState({
              modalSuccess: false,
              hasErrors: false,
              errorsArray: [],
              loading: false
            })
    
            this.props.resetArticle();
    
          }
    
  2. 使用jQuery选择按钮,然后使用.on函数将点击侦听器应用于返回的所有项目

    var buttons = document.getElementsByClassName('btn btn-success bank');
    for(var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", function(){
             $('#bankAssessBondId').append($(this).value)
        })
    }
    

我希望这会有所帮助!

答案 1 :(得分:0)

对于动态生成的元素,您需要使用delegated events函数的JQuery on()形式:

$('body').on('click', '.btn.btn-success.bank', function() {
    $('#bankAssessBondId').append($(this).value)
}

在这种情况下,我将“ body”用作父元素,但是它可以是任何作为按钮父元素的元素。

答案 2 :(得分:0)

当选择具有多个类的元素时,必须指定选择器,且不带空格,如下所示。

$('.btn.bank.btn-success')

在这种情况下,应该使用脚本打开模态,因为模态内的跨度值需要动态更改。

$('#bankAssess').modal('toggle');

$(function() {


  $('.btn.bank.btn-success').click(function() {

    var val = $(this).attr("value");

    console.log(val);

    $('#bankAssessBondId').append(val);
    $('#bankAssess').modal('toggle');

  });


});
#bankAssessBondId {
  color: red;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="modal fade" id="bankAssess" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabelBank" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabelBank">Bank Assess <span id="bankAssessBondId"></span></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
      </div>
      <div class="modal-body">
        <form>
          <div class="credit-scoring">
            <label for="credit-scoring" class="form-control-label">Credit Scoring:</label>
            <input type="text" class="form-control" id="credit-scoring">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" id="submit-form-Bank">Submit</button>
      </div>
    </div>
  </div>
</div>

<button class="btn btn-success bank" type="button" data-target="#bankAssess" value="bond2">
Bank Assess
</button>

<button class="btn btn-success bank" type="button" data-target="#bankAssess" value="bond3">
Bank Assess
</button>

答案 3 :(得分:0)

您可以使用按钮的类名获取按钮

$(".bank").on('click', function () {
  alert('clicked');
    $('#bankAssessBondId').append($(this).attr('value'));
});

还将按钮的值附加到id =“ bankAssessBondId”

<span id="bankAssessBondId"></span>
<button class="btn btn-success bank" type="button" data-toggle="modal" data-target="#bankAssess" value="bond3">
Bank Assess
</button>

使用示例代码

这是一个可行的示例。 https://codepen.io/anon/pen/oQGJOm