无法调用在同一父函数(DOM)中声明的函数

时间:2018-09-01 06:20:07

标签: javascript dom

问题已解决。它与功能无关,只是CSS优先级问题。

我在分配给window.onload的匿名函数中声明了一个名为AlternativeTableColor()的函数。此功能交替显示网页上表格的颜色。当调用它而不嵌套到任何其他函数时,它可以正常工作。但是,当它嵌套在同一环境中声明的另一个函数中时,它将无法工作。你能帮忙吗?

function my$(id) {
  return document.getElementById(id);
}

function deleteTr(oTr) {
  oTr.parentNode.removeChild(oTr);
}
  let currentId = 2;
  let oTable = document.getElementsByTagName('table')[0];
  let aAs = oTable.tBodies[0].getElementsByTagName('a');

  function alternateTableColor() {
    for (let i = 0; i < oTable.tBodies[0].rows.length; i++) {
      if (i % 2) {
        oTable.tBodies[0].rows[i].style.backgroundColor = 'lightgrey';
      } else {
        oTable.tBodies[0].rows[i].style.backgroundColor = '';
      }
    }
  }
  alternateTableColor();
  // add event to existing delete button
  for (let i = 0; i < aAs.length; i++) {
    aAs[i].onclick = function() {
      deleteTr(this.parentNode.parentNode);
    }
  }
  // add event to create button
  my$('create-entry').onclick = function() {
    // add all html data to a data array
    let data = [];
    data.push(++currentId);
    data.push(my$('add-name').value);
    data.push(my$('add-age').value);
    data.push('<a href="javascript:void(0)">Delete</a>');

    // create a <tr> element
    let oTr = document.createElement('tr');
    for (let i = 0; i < data.length; i++) {
      let oTd = document.createElement('td');
      oTd.innerHTML = data[i];
      oTr.appendChild(oTd);
    }
    oTable.tBodies[0].appendChild(oTr);

    // add click event to <a>Delete</a>
    let oA = oTr.getElementsByTagName('a')[0];
    oA.onclick = function() {
      deleteTr(this.parentNode.parentNode);
    }
  };
  // add event to search button
  my$('search-query').onclick = function() {
    alternateTableColor();
    let aQueries = my$('query').value.split(' ');
    console.log(aQueries);
    for (let i = 0; i < oTable.tBodies[0].rows.length; i++) {
      let source = (oTable.tBodies[0].rows[i].cells[1]).innerHTML.toLowerCase();
      for (let j = 0; j < aQueries.length; j++) {
        let target = aQueries[j].toLowerCase();
        if (source.search(target) != -1) {
          oTable.tBodies[0].rows[i].cells[1].style.backgroundColor = 'yellow';
        }
      }
    }
  }
  my$('clear-color').onclick = alternateTableColor;
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
}

thead tr {
  font-weight: bold;
  border-bottom: 2px double black;
}

/* tbody > :nth-child(even){
            background-color: lightgrey;
        } */

table {
  width: 100%;
}

.data-input {
  margin-bottom: 10px;
  position: relative;
}

.data-input::after {
  content: "";
  clear: both;
  display: block;
}

.box {
  width: fit-content;
  margin: 20px auto;
}

.search {
  /* float: right; */
  margin-top: 10px;
}

#query {
  box-sizing: border-box;
  width: calc(100% - 106px);
}

#search-query,
#create-entry {
  box-sizing: border-box;
  margin-left: 2px;
  width: 100px;
}

.ul-input {
  border: none;
  border-bottom-width: 2px;
  border-bottom-style: inset;
  border-bottom-color: initial;
  padding-left: 5px;
}

.ul-input:focus {
  outline: none;
}

.ul-input::placeholder,
.ul-input {
  text-align: center;
}

.ul-input:focus::placeholder {
  color: transparent;
}
<div class="box">
  <div class="data-input">
    <div class="add-new">
      <label for="add-name">Name: </label><input type="text" id="add-name" class="ul-input" placeholder="Enter name" />
      <label for="add-age">Age: </label><input type="number" id="add-age" class="ul-input" placeholder="Enter age" />
      <input type="button" id="create-entry" value="Create" />
    </div>
    <div class="search">
      <input type="text" id="query" class="ul-input" placeholder="What are you looking for?" />
      <input type="button" id="search-query" value="Search" /><br>
      <input type="button" id="clear-color" value="Clear Color" />
    </div>
  </div>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>John</td>
        <td>30</td>
        <td><a href="javascript:void(0)">Delete</a></td>
      </tr>
      <tr>
        <td>2</td>
        <td>June</td>
        <td>40</td>
        <td><a href="javascript:void(0)">Delete</a></td>
      </tr>
    </tbody>
  </table>
</div>

2 个答案:

答案 0 :(得分:0)

JavaScript按函数作用域变量。

function a() {  
  var b = 1;
  function c() {
  }
}
// b is undefined
// c is also undefined

https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Functions#Description

请注意,function c() {}等同于var c = function () {};

function a () {
 function b() {
    console.log('b');
 }
 function c() {
    console.log('c');
    b();
 }

 c();
}

a(); // prints c then b

答案 1 :(得分:0)

您可以调用函数您的有意位置。

import UIKit
import Alamofire

class LikeOperation: Operation {

    private var _isExecuting = false
    private var _finished = false
    private var request:DataRequest? = nil
    private var imageID:String

    typealias completionBlock = ((GeneralResponse<User>?) -> Void)?

    var finishedBlock : completionBlock

    init(imageID:String, completionBlock:completionBlock) {
        self.imageID = imageID
        self.finishedBlock = completionBlock
        super.init()

    }

    override var isExecuting: Bool {
        get {
            return _isExecuting
        } set {
            willChangeValue(forKey: "isExecuting")
            _isExecuting = isExecuting
            didChangeValue(forKey: "isExecuting")
        }
    }


    override var isFinished: Bool {
        get {
            return _finished
        } set {
            willChangeValue(forKey: "isFinished")
            _finished = newValue
            didChangeValue(forKey: "isFinished")
        }
    }

    override func start() {
        if isCancelled {
            isFinished = true

            return
        }

        isExecuting = true

        func completeOperation() {
            isFinished = true
            isExecuting = false

        }
        self.request =  APIClient.insertImageLike(ImageID: self.imageID, completion: { (completion:GeneralResponse<User>?, error) in

            self.finishedBlock?(completion!)
            completeOperation()
        })

    }

    override func cancel() {
        super.cancel()

        if isExecuting {
            isFinished = true
            isExecuting = false
        }

        request?.cancel()

    }


}



  func callAPIToLike (post:Post) {
        guard let id = post.id else {
            self.showAlert(withMessage: ErrorMessages.General.somethingWentWrong)
            return
        }

        AppGlobalManager.sharedInstance.homeScreenLikeAPIQueue.cancelAllOperations()
        let operation = LikeOperation.init(imageID: "\(id)") { (object) in

        }
        AppGlobalManager.sharedInstance.homeScreenLikeAPIQueue.addOperation(operation)

    }

这是JavaScript的词汇范围。 您可以研究此https://css-tricks.com/javascript-scope-closures/